1

だから、私はいくつかのphp OOのものに問題があります。コードがそれを最もよく説明すると思います:

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;
    }
}

ここで、foo テーブルに someprop があり、bar テーブルに otherprop があると仮定すると、ID を渡すと、オブジェクトに変数が設定されます。

しかし、何らかの理由で、foo は完全に機能しますが、bar は何も設定しません。

$this->setVar() 呼び出しでバラバラになり、間違った setVar を呼び出していると思いますが、get_class($this) が機能している場合 (これはそうです)、$this はバーであってはなりません。関連付け、setVar() は $bar メソッドになりますか?

私が行方不明/間違っていることを見た人はいますか?

4

1 に答える 1

3

サブクラスでプライベート メソッドをオーバーライドすることはできません。プライベート メソッドは、サブクラスではなく、実装するクラスのみが認識します。

ただし、これを行うことができます:

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;
    }
}
于 2010-09-21T00:45:54.870 に答える