我应该什么时候在PHP中设置类属性-在构造函数中还是在需要时设置?
我正在学习OOP PHP,我正在努力知道何时设置变量 我的类中有一堆变量,有些函数使用这些变量,但不是所有函数都使用。下面的代码显示了如果一个函数需要一个变量,它是如何运行的 1) 检查当前是否已设置 2) 如果未设置,则运行设置该变量的任何函数 这是对的,还是应该使用_构造函数设置所有变量 事先非常感谢——劳拉我应该什么时候在PHP中设置类属性-在构造函数中还是在需要时设置?,php,oop,Php,Oop,我正在学习OOP PHP,我正在努力知道何时设置变量 我的类中有一堆变量,有些函数使用这些变量,但不是所有函数都使用。下面的代码显示了如果一个函数需要一个变量,它是如何运行的 1) 检查当前是否已设置 2) 如果未设置,则运行设置该变量的任何函数 这是对的,还是应该使用_构造函数设置所有变量 事先非常感谢——劳拉 class Person { private $user_id; private $eye_color; public function __construct ($user_id
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;
}
}
我不认为有一个独特的方式来做这件事,这取决于每个案件 如果加载数据的函数(在您的例子中是
eyeColor()
)在资源或时间方面非常昂贵,那么让它只在需要时运行是一个不错的选择。如果它很简单,那么您可以在构造函数中运行它
还请记住,如果您打算使用may times的eye\u color
may,每次需要它时,您都会测试一个条件子句,看看它是否已经加载。因此,如果您多次使用该值,最好将其加载到构造函数中并保存这些条件测试
如果你确信你至少会使用它一次,最好把它放在构造函数中。在你的情况下,我认为你的
人
类是关闭的。如果“眼睛颜色”属于用户,那么它应该保留在那里,并且只能由Person
类暴露,不能在两个类中重复。请参阅以下代码更改:
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\u id
。这意味着人
对象如果没有用户id
就不可能存在,从而实现您想要的合成eyeColor()
公开get\u user\u meta($this->user\u id,“\u eye\u color”,“true”)
,这意味着人的眼睛颜色实际上只是对用户眼睛颜色属性的引用
我还认为,您应该传入一个
user\u id
,而不是一个user
对象,但这取决于您的代码是如何的,以及您希望将其传递多远。如果组成Person对象需要属性,则应该将其注入构造函数。一个粗略的类比是建造一辆汽车,你需要发动机、齿轮、轮子。。。但是在建造过程中不需要燃料,因此可以在以后需要执行操作(如移动汽车)时添加燃料。也可以说是发动机、齿轮、车轮。。在构造之后是不变的。这是一个很好的解释。谢谢。