【问题标题】:OOP: retrieve 'fathers' attributes from the 'child' objectOOP:从“孩子”对象中检索“父亲”属性
【发布时间】:2009-07-28 13:58:51
【问题描述】:

我又来了;)

我的问题在于嵌套的 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

有什么帮助吗?

【问题讨论】:

  • 作为旁注:让儿子扩展父亲在概念上意味着,你的儿子是父亲,这通常是不正确的。合理的做法是创建一个父类 Person ,它具有父类和子类都继承自它的公共属性。
  • 我必须同意 HerdplanttenToni 的观点。应用面向对象的原则将导致使用 Person 类,该类可以是儿子或父亲。使用父类和子类导致关系是数据模型而不是对象模型。

标签: php oop class inheritance


【解决方案1】:

除非你告诉儿子们他们的父亲是谁,否则你不能。这可以通过向儿子添加 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 方法中创建儿子,而是让该方法将已创建的儿子作为其参数。

【讨论】:

  • 你甚至可以使用 PHP 魔术方法让 $son->job() 自动去从父亲那里得到工作;但你仍然必须告诉儿子父亲是谁。
  • 布伦顿解决方案效果很好,但请解释一下“魔术方法”
  • 它不一定是魔法,它只是儿子中的一个方法,看起来像: public function getFatherJob() { return $this->getFather()->job;在大多数情况下,我个人宁愿链接方法,但取决于你。
猜你喜欢
  • 2021-10-22
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多