开发者

Accessing model that has the same name as a local variable

开发者 https://www.devze.com 2023-04-02 03:20 出处:网络
I\'m really confused because i have the following case: Class Game extends CI_Model{ $this->load->model(\'us开发者_Python百科er\');

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();

0

精彩评论

暂无评论...
验证码 换一张
取 消