downcasting in php5

2019-03-05 22:00发布

I've realized that there's no downcasting in php5. Is there a common pattern to achieve it?

标签: php downcast
1条回答
The star\"
2楼-- · 2019-03-05 22:39

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);
查看更多
登录 后发表回答