在php5中向下转发

时间:2009-11-12 12:46:20

标签: php downcast

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

1 个答案:

答案 0 :(得分: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);