[英]How to instantiate object of $this class from within the class? PHP
我有一个这样的课:
class someClass {
public static function getBy($method,$value) {
// returns collection of objects of this class based on search criteria
$return_array = array();
$sql = // get some data "WHERE `$method` = '$value'
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$new_obj = new $this($a,$b);
$return_array[] = $new_obj;
}
return $return_array;
}
}
我的问题是:我可以像上面一样使用$ this吗?
代替:
$new_obj = new $this($a,$b);
我可以写:
$new_obj = new someClass($a,$b);
但是当我扩展类时,我将不得不重写该方法。 如果第一个选项有效,则无需这样做。
解决方案更新:
这些都在基类中起作用:
1.)
$new_obj = new static($a,$b);
2.)
$this_class = get_class();
$new_obj = new $this_class($a,$b);
我还没有在儿童班上尝试过它们,但是我认为#2在那里会失败。
另外,这不起作用:
$new_obj = new get_class()($a,$b);
它会导致解析错误:意外的'('必须分两步完成,如上面的2.)所述,或者更好的是如1.)所述。
简单,使用static
关键字
public static function buildMeANewOne($a, $b) {
return new static($a, $b);
}
参见http://php.net/manual/en/language.oop5.late-static-bindings.php 。
您可以使用ReflectionClass :: newInstance
class A
{
private $_a;
private $_b;
public function __construct($a = null, $b = null)
{
$this->_a = $a;
$this->_b = $b;
echo 'Constructed A instance with args: ' . $a . ', ' . $b . "\n";
}
public function construct_from_this()
{
$ref = new ReflectionClass($this);
return $ref->newInstance('a_value', 'b_value');
}
}
$foo = new A();
$result = $foo->construct_from_this();
尝试使用get_class(),即使继承了该类,此方法也有效
<?
class Test {
public function getName() {
return get_class() . "\n";
}
public function initiateClass() {
$class_name = get_class();
return new $class_name();
}
}
class Test2 extends Test {}
$test = new Test();
echo "Test 1 - " . $test->getName();
$test2 = new Test2();
echo "Test 2 - " . $test2->getName();
$test_initiated = $test2->initiateClass();
echo "Test Initiated - " . $test_initiated->getName();
运行时,您将获得以下输出。
测试1-测试
测试2-测试
测试启动-测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.