让一个孩子在PHP中扩展已初始化的父级

Mat*_*att 2 php oop inheritance

我一直很难找到这个解决方案.我希望你们都能帮助我.

最好用一个例子来描述:

class Parent {
    public $nationality;

    function __construct($nationality)
    {
        $this->nationality = $nationality
    }
}

class Child extends Parent {
    function __construct() {
        echo $this->nationality; // hispanic
    }
}

// Usage:
$parent = new Parent('hispanic');
$child = new Child();
Run Code Online (Sandbox Code Playgroud)

我希望孩子从已经初始化的父级继承属性和方法.


编辑:谢谢大家的回复 - 让我给你一些背景知识.我正在尝试制作一个模板系统.我有两个类 - 比如Tag.php和Form.php.

我希望它看起来像这样:

class Tag {
    public $class_location;
    public $other_tag_specific_info;
    public $args;

    function __construct($args)
    {
        $this->args = $args;
    }

    public function wrap($wrapper) {
        ...
    }

    // More public methods Form can use.
}

class Form extends Tag {
    function __construct() {
        print_r($this->args()) // 0 => 'wahoo', 1 => 'ok'
        echo $this->class_location; // "/library/form/form.php"
        $this->wrap('form');
    }

    function __tostring() {
        return '<input type = "text" />';
    }
}

// Usage:
$tag = new Tag(array('wahoo', 'ok'));
$tag->class_location = "/library/form/form.php";
$tag->other_tag_specific_info = "...";
$form = new Form();
Run Code Online (Sandbox Code Playgroud)

我不喜欢复合模式的原因是我没有理由为什么我会将Tag的实例传递给它的一个子类的构造函数,afterall - Form是一种Tag吗?

谢谢!马特穆勒

Den*_*huk 7

你想做的事情可以说是糟糕的设计.如果您创建Parent具有不同国籍的多个实例然后创建新Child实例会发生什么.这个孩子接受哪个国籍?

为什么不让Child类成为复合体,在构造函数中给它一个父类?

class Child
{
    private $parent;

    function __construct($parent)
    {
        $this->parent = $parent;
    }

    function getNationality()
    {
        return $this->parent->nationality;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用它创建它

$parent = new Parent('hispanic');
$child = new Child($parent);
Run Code Online (Sandbox Code Playgroud)

或者用父母的工厂方法......其余的都取决于你的想象力.


注意:我忽略了这样一个事实:我没有在父类中使用getter获取国籍,也没有为Child提供超类(Parent也许?不是很有意义).这些都是与设计相关的要点,但不在此问题的范围内.