是否可以在Codeigniter模型中添加__get和__set ?


Is it possible to add __get and __set to Codeigniter Model?

我想在模型中使用__get__set,但它不起作用,而不是为每列设置getter和setter。

这里有一个例子:

class Video extends CI_Model {
  private $video_id = null;
  private $title;
  private $url;
  private $thumb;
  private $width;
  private $height;
 public function __set($name, $value){
    if(!$this->video_id) return false;
    if(property_exists($this, $name))
    {
       $data = array(
          $name      => trim($this->security->xss_clean($value)),
      'updated'  => date('Y-m-d H:i:s'),
      );
      if($this->db->update('users', $data, array('video_id' => (int)$this->video_id)))
      {
          return $this->db->affected_rows();
      }
      else
      {
      return $this->db->_error_message();
      }
    }
 }
}

然后从我的控制器我做:

$this->video->width(780);

生产:

<b>Fatal error</b>:  Call to undefined method Video::width() in <b>/home/crazy/public_html/dev/application/controllers/admin.php</b> on line <b>169</b><br />

首先,您需要仔细阅读有关这些内容的文档。你用错了魔法方法。__set用于设置对象属性:

$obj->width = 780; // Will be translated to:
$obj->__set('width', 780);

如果您使用__call,那么方法将被重载:

$obj->width(780); // Will be translated to:
$obj->__call('width', array(780));

其次,您需要查看CI_Model的CI源代码。如果我链接到正确的版本,然后它设置自己的__get方法,如果你想设置自己的getter,你必须考虑。