简体   繁体   中英

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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