【问题标题】:PHP: Chaining Class Variables (Not Methods)PHP:链接类变量(不是方法)
【发布时间】:2013-08-01 23:48:41
【问题描述】:

所以我了解如何链接方法,但我对链接变量感兴趣。这可以在PHP中做到吗?以下是我设想的用法示例:

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(){}
}

如您所见,我希望链接的示例代码中的两个变量是:

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

但我不确定如何实现变量链接,也不知道这是否可行。我之所以要这样做是因为我喜欢将所有内容分类以进行维护。

【问题讨论】:

  • 想想吧!! $this->color->eyes 的结果是什么
  • 我的问题是,我可以将 $this->color->eyes 设为合法变量,而不是 $this->color()->eyes 吗?在这种情况下,我希望颜色成为外套和眼睛的父母。

标签: php variables chaining


【解决方案1】:

不在一个班级,不。

顺便说一句,考虑类和继承的逻辑方式是让眼睛有颜色,而不是颜色有眼睛!就像你有一个 Dog 类一样,Dog 有眼睛,而狗的眼睛有颜色。

但是,如果您创建一个名为 Color 的基类,然后创建一个名为 Eyes 的类来扩展 Color 类,然后再创建一个名为 Coat 的类来扩展 Color 类,您可以实现类似的效果。

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 2017-09-16
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多