如何根据当前创建新对象?

时间:2013-12-18 06:35:55

标签: php html class methods abstract-class

我有一个基类和多个从基类扩展的类。

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();

1 个答案:

答案 0 :(得分:0)

你是对的!但是你必须返回你的新对象,如:

class B {

    function hello() { echo "hello"; }

    function createObject()
    {
        $temp = new self();
        $temp->hello();
        return $temp; // <--- here
    }
}

$t = new C();
$tNew = $t->createObject();