gpt4 book ai didi

php - 让一个 child 在 PHP 中扩展一个已经初始化的 parent

转载 作者:行者123 更新时间:2023-12-04 20:25:56 24 4
gpt4 key购买 nike

我一直很难找到解决这个问题的方法。希望大家能帮帮我。

最好用一个例子来描述:

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();

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


编辑:感谢大家的回复 - 让我给你一些背景知识。我正在尝试制作一个模板系统。我有两个类 - 比如 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();

我不喜欢复合模式的原因是它不我明白为什么我会将 Tag 的实例传递给构造函数它的一个子类,毕竟 - Form 是一种 Tag 对吗?

谢谢!马特·穆勒

最佳答案

你想做的可以说是糟糕的设计。如果您创建多个具有不同国籍的 Parent 实例,然后创建一个新的 Child 实例,会发生什么情况。那么这个 child 是哪个国籍的呢?

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

class Child
{
private $parent;

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

function getNationality()
{
return $this->parent->nationality;
}
}

然后用

创建它
$parent = new Parent('hispanic');
$child = new Child($parent);

或者使用来自父级的工厂方法...剩下的就看你的想象了。


注意:我忽略了一个事实,即我没有在父类上使用国籍的 setter/getter ,也没有为子类提供父类(super class)(也许是父类?真的没有意义) .这些东西都是设计相关的点,但不在这个问题的范围内。

关于php - 让一个 child 在 PHP 中扩展一个已经初始化的 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3080465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com