Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 访问与局部变量同名的模型_Php_Codeigniter - Fatal编程技术网

Php 访问与局部变量同名的模型

Php 访问与局部变量同名的模型,php,codeigniter,Php,Codeigniter,我真的很困惑,因为我有以下情况: Class Game extends CI_Model{ $this->load->model('user'); public $user = 'foo'; $var = $this->user; // Model Or Local Variable? } 我如何判断它应该使用哪一个,模型User还是本地公共变量$User?$this->User与$User不同 使用$this->load->model('user')加载的模型

我真的很困惑,因为我有以下情况:

Class Game extends CI_Model{
  $this->load->model('user');
  public $user = 'foo';

  $var = $this->user; // Model Or Local Variable?
}

我如何判断它应该使用哪一个,模型
User
还是本地公共变量
$User

$this->User
$User
不同

使用
$this->load->model('user')加载的模型
只能通过
$this
变量访问。此外,您应该只通过模型已经放置在其中的变量范围来访问它(如果您愿意,这更有意义)

本地方法变量,正如您尝试使用
$var=$this->user,只能通过方法访问

因此,更正您的代码时,它看起来是这样的:

Class Game extends CI_Model{

    public function get_player() {
      $this->load->model('user'); // Load the User model

      $user = 'foo'; // Variable with the string value 'foo'.

      $var = $this->user; 
      // $var is a copy of the model you loaded before
      // which means using:
      $name = $this->user->get_username();
      // is the same as
      $name = $var->get_username();

      retun $name;

    }
}

简单快速的解决方案:

If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function: $this->load->model('Model_name', 'fubar'); $this->fubar->function(); 如果希望将模型指定给其他对象名称,可以通过加载函数的第二个参数指定: $this->load->model('model_name','fubar'); $this->fubar->function();
你的代码真的有点乱。但是,
$此
总是指对象。