1

我已经意识到 php5 中没有向下转换。有没有共同的模式来实现它?

4

1 回答 1

1

您可以将派生类设置为将 BaseClass 对象作为构造函数中的参数,然后从中复制属性:

class Base {
    var $x, $y;
}

class DerivedClass extends Base {
    function __construct($param) {
         $this->copyFromBase($param); // put some type-checking here...
    }

    function copyFromBase($base) {
        $this->x = $base->x;    // you could definitely use a more
        $this->y = $base->y;    // intelligent way to do this
    }
}

$b = new Base();
$b->x = 'X';
$b->y = 'Y';
$b = new Derived($b);
于 2009-11-12T12:53:19.743 回答