从__construct函数声明对象的属性(declare properties of an object out of __construct function)
我想知道声明一个对象的属性是否是一个好习惯,如:
$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
函数上声明一切?I would like to know if is a good practice to declare a property of an object like:
$this->name = $name;
out of the function
__construct
I am trying to build an object with data from a database table. But this object will be build only if the id is registered. I know that the __construct function always return an object so I can not get a false return. So I tried the following:
//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; } } }
This will work but is a good practice to do it like this? or I should declare everything on the
__construct
function?
原文:https://stackoverflow.com/questions/44534813