views:

14

answers:

1

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?

+2  A: 

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;
    }
}
Sam Day
Augh duhh! Thanks!
Jesse
@Jesse: No worries :) Flag this as answered if you would please ;)
Sam Day