当方法在父类中时,如何返回被调用类的实例。
EG。在下面的示例中,如果我致电B
,如何返回B::foo();
的实例?
abstract class A
{
public static function foo()
{
$instance = new A(); // I want this to return a new instance of child class.
... Do things with instance ...
return $instance;
}
}
class B extends A
{
}
class C extends A
{
}
B::foo(); // Return an instance of B, not of the parent class.
C::foo(); // Return an instance of C, not of the parent class.
我知道我可以这样做,但有一种更简洁的方式:
abstract class A
{
abstract static function getInstance();
public static function foo()
{
$instance = $this->getInstance(); // I want this to return a new instance of child class.
... Do things with instance ...
return $instance;
}
}
class B extends A
{
public static function getInstance() {
return new B();
}
}
class C extends A
{
public static function getInstance() {
return new C();
}
}
答案 0 :(得分:18)
$instance = new static;
您正在寻找Late Static Binding。
答案 1 :(得分:1)
http://www.php.net/manual/en/function.get-called-class.php
<?php
class foo {
static public function test() {
var_dump(get_called_class());
}
}
class bar extends foo {
}
foo::test();
bar::test();
?>
结果
string(3) "foo"
string(3) "bar"
所以你的功能将是:
public static function foo()
{
$className = get_called_class();
$instance = new $className();
return $instance;
}
答案 2 :(得分:0)
您只需要:
abstract class A {
public static function foo() {
$instance = new static();
return $instance ;
}
}
或者
abstract class A {
public static function foo() {
$name = get_called_class() ;
$instance = new $name;
return $instance ;
}
}