downcasting in php5

后端 未结 1 2020
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-25 15:01

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

相关标签:
1条回答
  • 2021-01-25 16:07

    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 讨论(0)
提交回复
热议问题