【问题标题】:declare properties of an object out of __construct function从 __construct 函数中声明对象的属性
【发布时间】: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


【解决方案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();

【讨论】:

  • 太棒了,这对我来说很有意义......我需要了解更多关于这个注射部分的信息,但我一定会听从你的建议
猜你喜欢
  • 2021-09-03
  • 2011-01-13
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
相关资源
最近更新 更多