从__construct函数声明对象的属性

时间:2017-06-14 03:16:25

标签: php

我想知道声明一个对象的属性是否是一个好习惯,如:

$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函数上声明所有内容?

1 个答案:

答案 0 :(得分:1)

做你正在做的事情很好,但我认为将数据库注入构造并将id引入验证更有意义。创建setId()也很有价值:

class item
    {
        protected $id,
                  $db;
        # Inject the $db instead
        public function __construct(db $db)
            {
                $this->db = $db;
            }
        # Inject the id here
        public function validate($id = false)
            {
                if(!empty($id))
                    $this->id = $id;

                if($mod = $this->db->get($this->getId())) {
                    $this->price = $mod['price'];
                    $this->name = $mod['name'];
                    $this->desc = $mod['desc'];
                    return true;
                } else {
                    return false;
                }
            }
        # Create a method that can assign so you can reused the object
        public function setId($id)
            {
                $this->id = $id;
                # Return the object for chaining
                return $this;
            }
        # Have a method to get current id
        public function getId()
            {
                return $this->id;
            }
    }

# Create instance, inject db class
$mod = new item(new db('restaurants_items_modifiers'));
# Inject the id here
if($mod->validate($id)) {
    $item = $mod;
}

您也可以重置此ID。它们基本上与注入validate()相同,但它取决于您希望能够在线下$id访问多少(可能将其private转为将其锁定可能需要直接访问):

$mod->setId($id)->validate();
相关问题