开发者

overriding PHP class methods referenced by non-overridden $this

开发者 https://www.devze.com 2023-01-17 02:51 出处:网络
So, I\'m having trouble with some php OO stuff. I think the code will explain it best: class foo { $someprop;

So, I'm having trouble with some php OO stuff. I think the code will explain it best:

class foo {

    $someprop;

    public function __construct($id){
        $this->populate($id);
    }
    private function populate($id){
        global $db;
        // obviously not the call, but to illustrate the point:
        $items = $db->get_from_var1_by_var2(get_class($this),$id);
        while(list($k,$v) = each($items)){
            $this->setVar($k,$v);
        }
    }
    private function setVar($k,$v){
        // filter stuff, like convert JSON to arrays and such.
        $this->$k = $v;
    }
}

class bar extends foo {

    $otherprop;

    public function __construct($id){
        parent::__construct($id);
    }
    private function setVar($k,$v){
        // different filters than parent.
        $this->$k = $v;
    }
}

Now, assuming my foo table has someprop in it, and my bar table has otherprop in开发者_运维问答 it, this should set the vars on my object when I pass in an ID.

But, for some reason, foo works perfectly, but bar doesn't set anything.

My assumption is that it is falling apart on the $this->setVar() call, and calling the wrong setVar, but if get_class($this) is working (which it is), shouldn't $this be bar, and by association, setVar() be the $bar method?

Anyone see something I'm missing/doing wrong?


You cannot override private methods in subclasses. A private method is known to the implementing class ONLY, not even subclasses.

You CAN do this though:

class foo {

    $someprop;

    public function __construct($id){
        $this->populate($id);
    }
    private function populate($id){
        global $db;
        // obviously not the call, but to illustrate the point:
        $items = $db->get_from_var1_by_var2(get_class($this),$id);
        while(list($k,$v) = each($items)){
            $this->setVar($k,$v);
        }
    }
    protected function setVar($k,$v){
        // filter stuff, like convert JSON to arrays and such.
        $this->$k = $v;
    }
}

class bar extends foo {

    $otherprop;

    public function __construct($id){
        parent::__construct($id);
    }
    protected function setVar($k,$v){
        // different filters than parent.
        $this->$k = $v;
    }
}
0

精彩评论

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