【发布时间】:2017-06-14 03:16:25
【问题描述】:
我想知道声明对象的属性是否是一种好习惯,例如:
$this->name = $name;
退出函数__construct
我正在尝试使用数据库表中的数据构建一个对象。但是这个对象只有在注册了 id 时才会被构建。我知道 __construct 函数总是返回一个对象,所以我不能得到错误的返回。所以我尝试了以下方法:
//test.php
$mod = new item($id);
if($mod->validate()) {
$item = $mod;
}
class item {
protected $id;
public function __construct($id) {
$this->id = $id;
}
public function validate() {
$db = new db('restaurants_items_modifiers');
if($mod = $db->get($this->id)) {
$this->price = $mod['price'];
$this->name = $mod['name'];
$this->desc = $mod['desc'];
return true;
} else {
return false;
}
}
}
这会起作用,但这样做是个好习惯吗?或者我应该在__construct 函数上声明所有内容?
【问题讨论】:
-
我要做的一个改变是注入你的数据库连接,而不是在
validate()方法中。 -
没关系。您可以在此问题中查看更多信息What is the function __construct used for?
-
另外,将数据库注入
__construct($db)和$id注入validate($id)可能更有意义
标签: php