我意识到php5中没有向下转换。是否有共同的模式来实现它?
答案 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);