我希望在父类中有一个静态方法,它创建我调用此方法的子类的实例.
一个让这个更清晰的例子:
class parent { public static method make_objects($conditions){ for (...){ // here i want to create an instance // of whatever subclass i am calling make_objects on // based on certain $conditions } } } class sub extends parent{ ... } $objects = sub::make_objects($some_conditions);
从PHP 5.3开始,您可以使用
static关键字
<?PHP class A { public static function newInstance() { $rv = new static(); return $rv; } } class B extends A { } class C extends B { } $o = A::newInstance(); var_dump($o); $o = B::newInstance(); var_dump($o); $o = C::newInstance(); var_dump($o);
版画
object(A)#1 (0) { } object(B)#2 (0) { } object(C)#1 (0) { }
编辑:另一个(类似的)例子
<?PHP class A { public static function newInstance() { $rv = new static(); return $rv; } public function __construct() { echo " A::__construct\n"; } } class B extends A { public function __construct() { echo " B::__construct\n"; } } class C extends B { public function __construct() { echo " C::__construct\n"; } } $types = array('A','B','C'); foreach( $types as $t ) { echo 't=',$t,"\n"; $o = $t::newInstance(); echo ' type of o=',get_class($o),"\n"; }
版画
t=A A::__construct type of o=A t=B B::__construct type of o=B t=C C::__construct type of o=C