Accessing model that has the same name as a local variable
I'm really confused because i have the following case:
Class Game extends CI_Model{
$this->load->model('us开发者_Python百科er');
public $user = 'foo';
$var = $this->user; // Model Or Local Variable?
}
How can i tell which one should it use, the Model User
or the local public variable $user
?
$this->user
is not the same as $user
The model you loaded with $this->load->model('user');
is only accessable through the $this
variable. Furthermore, you should only acccess it through the variable scope which the model already is placed in (makes more sense, if you will).
Local method variables, as you're trying to do with $var = $this->user;
, is only accessable through a method.
So, correcting your code, it would look something like this:
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;
}
}
Simple and fast solution :
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();
精彩评论