开发者

downcasting in php5

开发者 https://www.devze.com 2022-12-11 19:24 出处:网络
I\'ve realized that there\'s no downcasting in php5. Is开发者_如何学Go there a common pattern to achieve it? You could set the derived class to take a BaseClass object as a parameter in the constructo

I've realized that there's no downcasting in php5. Is开发者_如何学Go there a common pattern to achieve it?


You could set the derived class to take a BaseClass object as a parameter in the constructor, and then copy the properties from that:

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

精彩评论

暂无评论...
验证码 换一张
取 消