我在尝试在静态函数中调用CodeIgniter方法时遇到了问题,仅仅使用$this不起作用,因为它不在对象上下文中,static关键字也不起作用。这是我的核心模型中的代码示例,$table变量是从另一个类似posts的模型中成功定义的。
class MY_Model extends CI_Model {
protected static $table;
public function __construct() {
parent::__construct();
}
public static function find_all() {
$this->db->select('*');
$sql = $this->db->get(static::$table);
return $sql->result();
}
}
如果$this不起作用,你可以这样绕过:
$CI=&get_instance();$CI->db->
loader类中内置的codeigniter会自动实例化该类。不支持在不实例化的情况下使用类。您可以手动将文件包含在模型文件中,然后再使用它。有关更多详细信息,请查看此线程:http://codeigniter.com/forums/viewthread/73583/
您想要的是引用类中的静态var,因此使用:
class MY_Model extends CI_Model {
protected static $table;
public function __construct() {
parent::__construct();
}
public static function find_all() {
$this->db->select('*');
$sql = $this->db->get(self::$table);
return $sql->result();
}
}
当然,$table确实需要有一个值!
Codeigniter通常不支持静态方法,我认为它们实际上是试图将过程代码硬塞进面向对象的代码中。
无论如何,我认为您最好的选择是使用没有静态方法的类,或者将代码变成"助手"。助手只是一个老派函数库。您可以在helpers文件夹下创建它,并且可以使用$this->load->helper('helper_name')加载它。然后,您可以像在普通过程代码中一样调用该函数,换句话说就是"find_all()"
希望这能有所帮助。首次贡献者:)