简体   繁体   English

PHP:链接类变量(不是方法)

[英]PHP: Chaining Class Variables (Not Methods)

So I understand how to chain methods, but I am interested in chaining variables. 因此,我了解如何链接方法,但是我对链接变量感兴趣。 Is this possible to do in PHP? 这可以在PHP中完成吗? Here is an example of how I envision the usage: 这是我如何设想用法的示例:

Class Dog {
public $color; (Parent color)
public $eyes; (Child of color)
public $coat; (Child of color)

//Initialize dog
function __construct($color_eyes, $color_coat){
     $this->color->eyes = $color_eyes;
     $this->color->coat = $color_coat;
}

//Methods here, etc
function bark(){}
function walk(){}
}

As you can see, the two variables in the sample code I wish to chain are: 如您所见,我希望链接的示例代码中的两个变量是:

$this->color->eyes
$this->color->coat

But I am unsure how to accomplish variable chaining, nor do I know if this is possible. 但是我不确定如何完成变量链接,也不确定是否可行。 The reason why I would like to do this is because I like to categorize everything for maintenance purposes. 之所以要这样做,是因为我出于维护目的而将所有内容归类。

Not in a single class, No. 没有一个班级,没有。

By the way, the logical way of thinking about classes and inheritance would be to have eyes that have color and not color that have eyes! 顺便说一句,关于类和继承的逻辑思考方式是拥有有颜色的眼睛而不是有颜色的眼睛! As you have a Dog class, a Dog has Eyes and a dogs eyes have a color. 当您有“狗”类时,“狗”具有眼睛,“狗眼”具有颜色。

However, if you create a base class called Color, and then a class called Eyes that extends the Color class and then a class called Coat that extends the Color class you can achieve something like it. 但是,如果创建一个名为Color的基类,然后创建一个名为Eyes的类来扩展Color类,然后创建一个名为Coat的类来扩展Color类,则可以实现类似的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM