我应该何时在PHP中设置我的类属性 - 在构造函数中或何时需要它们?

时间:2018-01-16 21:25:19

标签: php oop

我正在学习OOP PHP,我很难知道何时设置我的变量。

我的课程中有很多变量,但有些变量并非所有函数都使用过。下面的代码显示了函数是否需要变量

1)检查当前是否已设置

2)如果未设置,则运行变量

的任何函数集

这是正确的,还是应该使用__constructor函数设置所有变量?

非常感谢 - 劳拉。

class Person {

private $user_id;
private $eye_color;

public function __construct ($user_id) {

    $this->user_id = $user_id;

}


public function eyeColor () {

    $this->eye_color = get_user_meta($this->user_id, '_eye_color', 'true');

}

public function describeEyes () {

    // If Eye Color Is not set, set it
    if (!isset($this->eye_color)) {
        $this->eyeColor();
    }

    $eye_decription = 'The user has beautiful eyes, they are' . $this->eye_color;

    return $eye_decription;

}

public function describeFace () {

    // If Eye Color Is not set, set it
    if (!isset($this->eye_color)) {
        $this->eyeColor();
    }

    $face_decription = 'The user has a nice face and beautiful eyes, they are' . $this->eye_color;

    return $face_decription;
}

}

2 个答案:

答案 0 :(得分:2)

我不认为这是一种独特的方式,这取决于每种情况。

如果加载数据的函数(在您的情况下为eyeColor())在资源或时间方面是昂贵的,那么只在需要时才运行它是一个不错的选择。如果它很简单,那么你可以在构造函数中运行它。

另请注意,如果您打算使用eye_color可能的次数,每次需要时,您都要测试条件子句以查看它是否已经加载。因此,如果您使用此值太多次,最好在构造函数中加载它并保存这些条件测试。

如果您确定至少使用过一次,请将其更好地放入构造函数中。

答案 1 :(得分:1)

在您的情况下,我会争辩说Person课程的Object Composition已关闭。如果"眼睛颜色"属于用户,然后是它应该保留的位置,它应该只由class Person { private $user_id; public function __construct($user_id) { $this->user_id = $user_id; } public function eyeColor() { return get_user_meta($this->user_id, '_eye_color', 'true'); } public function describeEyes() { return 'The user has beautiful eyes, they are' . $this->eyeColor(); } public function describeFace() { return 'The user has a nice face and beautiful eyes, they are' . $this->eyeColor(); } } 类公开,而不是在两个类之间重复。请参阅以下代码更改:

user_id

这里需要注意的一些事项:

  1. 我们只是通过构造函数设置Person。这意味着如果没有user_idget_user_meta($this->user_id, '_eye_color', 'true')对象就不可能存在,从而实现您所追求的构图。
  2. 我们通过函数eyeColor()展示Person,这意味着user_id的眼睛颜色实际上只是对用户眼睛颜色属性的引用。
  3. 我们永远不会在人的眼睛颜色和潜在用户的眼睛颜色之间产生不匹配,因为我们无法根据用户的眼睛颜色改变人的眼睛颜色。
  4. 我会进一步争辩说,你应该而不是传递User传递{{1}}个对象,但这取决于你的代码OO的方式以及你的距离想要接受它。