我有一个基类和多个从基类扩展的类。
class B {}
class C extends B {}
class D extends B {}
如何从 B 在方法中动态创建 C 或 D?最好的方法是什么?
例如,我尝试过:
class B {
function hello() { echo "hello"; }
function createObject()
{
$temp = new self();
$temp->hello();
}
}
$t = new C();
$t->createObject();
你是对的!但是您必须返回新对象,如下所示:
class B {
function hello() { echo "hello"; }
function createObject()
{
$temp = new self();
$temp->hello();
return $temp; // <--- here
}
}
$t = new C();
$tNew = $t->createObject();