在CodeIgniter中设置模型成员变量


Setting a model member variable in CodeIgniter

我正在使用CodeIgniter,并希望为模型设置一个成员变量。

我希望这样写代码:

class Person extends CI_Model {
    var $id = '';
    function __construct()
    {
        parent::__construct();
    }
    function set_id($id = '')
    {
        $this->id = $id;
    }
}

,然后我希望调用模型并像这样设置成员变量:

$person1 = $this->load->model('Person');
$person1->set_id(5000);

但是这给出了:

Fatal error: Call to a member function set_id() on a non-object

我显然在这里遗漏了一些PHP或CodeIgniter语言语义。有什么建议吗?

change this

$person1 = $this->load->model('Person');
$person1->set_id(5000);

$this->load->model('Person');
$this->Person->set_id(5000);
从文档

编辑

单个模型的不同实例

$this->load->model('Person', 'Person1');
$this->Person1->set_id(5000);
$this->load->model('Person', 'Person2');
$this->Person2->set_id(5000);

您需要使用与您的类同名的对象来访问模型函数。

一旦加载,你将使用与你的类同名的对象访问你的模型函数:$ this -> Model_name ->()函数;

应该是…

$this->load->model('Person');
$this->Person->set_id(5000);

$this->load->model('Person', 'somename');
$this->somename->set_id(5000);

你可以在这里查看文档