OOP:从'child'对象中检索'父亲'属性

时间:2009-07-28 13:58:52

标签: php oop class inheritance

这里我又来了;)

我的问题atm是嵌套的php类,例如,我有一个像这样的类:

class Father{
    public $father_id;
    public $name;
    public $job;
    public $sons;
    public function __construct($id, $name, $job){
        $this->father_id = $id;
        $this->name = $name;
        $this->job = $job;
        $this->sons = array();
    }

    public function AddSon($son_id, $son_name, $son_age){
        $sonHandler = new Son($son_id, $son_name, $son_age);
        $this->sons[] = $sonHandler;
        return $sonHandler;
    }

    public function ChangeJob($newJob){
        $this->job = $newJob;
    }
}

class Son{
    public $son_id;
    public $son_name;
    public $son_age;
    public function __construct($son_id, $son_name, $son_age){
        $this->son_id = $son_id;
        $this->son_name = $son_name;
        $this->son_age = $son_age;
    }
    public function GetFatherJob(){
        //how can i retrieve the $daddy->job value??
    }
}

就是这样,一个无用的课来解释我的问题。 我想做的是:

$daddy = new Father('1', 'Foo', 'Bar');
//then, add as many sons as i need:
$first_son = $daddy->AddSon('2', 'John', '13');
$second_son = $daddy->AddSon('3', 'Rambo', '18');
//and i can get here with no trouble. but now, lets say i need
//to retrieve the daddy's job referencing any of his sons... how?
echo $first_son->GetFatherJob(); //?

所以,每个儿子必须彼此独立,但是要继承父亲的属性和价值观。

我尝试过继承:

class Son extends Father{
[....]

但是我每次添加一个新的儿子时都必须声明父属性。其他父亲的属性将是 null

任何帮助?

1 个答案:

答案 0 :(得分:3)

除非你告诉儿子他们的父亲是谁,否则你不能。这可以通过向son添加setFather()方法并调用父的addSon()方法来完成。

例如

class Son {
    protected $_father;
    // ...
    public function setFather($father) {
        $this->_father = $father;
    }

    public function getFather() {
        return $this->_father;
    }
}

class Father {
    // ...
    public function AddSon($son_id, $son_name, $son_age){
        $sonHandler = new Son($son_id, $son_name, $son_age);
        $sonHandler->setFather($this);
        $this->sons[] = $sonHandler;
        return $sonHandler;
    }
}

作为旁注,我不会在AddSon方法中创建子,我会让该方法将已经创建的子作为其参数。