在codeigniter中字符串$this->load->模型中的每个部分究竟是什么意思?在下面的代码"$this"使参考用户类(控制器)?另外,它是否调用调用模型的方法load ?或者$this引用每个函数的名称吗?
<?php
class User extends CI_Controller {
function __construct()
{
parent::__construct();
$this->template->set_layout('adminLayout.php');
$this->load->model("User_model");
$this->load->Model('Auth_model');
}
function index()
{
$this->Auth_model->isLoggedIn();
$this->template->title('Admin ::');
$this->template->build('admin/index');
}
?>
$这是指您所在的类。$this不是来自CodeIgniter,而是来自PHP。$this指向当前对象。
模型通常是用来处理所有数据库关系的所以基本上这一行
$this->load->model("User_model");
表示"加载模型的名称",以便我们可以使用它。
每当你创建一个类
$something = new SomeClass();
那么$this
指的是由SomeClass创建的实例,在本例中是$something。无论何时在类本身中,都可以使用$this来引用这个实例。所以:
class SomeClass {
public $stuff = 'Some stuff';
public function doStuff()
{
$this->stuff;
}
}
$this
是指全局CodeIgniter对象。如果在构造函数或被调用的方法中使用var_dump($this)
,您将看到所有调用和初始化的代码。你可以跟踪变化的方式,你可以加载一些库,助手,方法,语言,包或配置或Loader.php
类框架允许的任何其他东西。您将得到与输出get_instance()
函数类似的输出。
该构造使用Config.php核心系统文件的load()
方法,您可以在第119行检查start。模型在线意味着需要加载的文件类型。基本上,它指的是Config类的加载方法,该方法作用于所需的Loader类方法(model, helper等)。
这意味着你正在加载模型(User_model和Auth_model),所以你可以使用这些模型内部的函数。例如:如果您有如下的Auth_model
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Auth_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function insert_valid_val($valid_data)
{
//Write queries here and return some values.
}
然后在控制器中调用insert_valid_val(),如下所示。
<?php
class User extends CI_Controller {
function __construct()
{
parent::__construct();
$this->template->set_layout('adminLayout.php');
$this->load->model("User_model");
$this->load->Model('Auth_model');
}
function index()
{
$this->Auth_model->isLoggedIn();
$this->template->title('Admin ::');
$this->template->build('admin/index');
$returned_val = $this->Auth_model->insert_valid_val("send some array");
print_r($retunred_val);
}
?>