CodeIgniter Forums

Full Version: Using class in model
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey guys,

I have a weird problem and i can't figure out how to solve it...

I have a custom library User.php with de following code:
PHP Code:
defined('BASEPATH') OR exit('No direct script access allowed');

class 
User
{
 
   public $session_prefix 'usrs_';

 
   public $cookie_prefix 'usrc_';

 
   public function __construct()
 
   {
 
       $this->load->model('users_model');

 
       $this->users_model->login_remembered_user();
 
   }

 
   public function __get($var)
 
   {
 
       return get_instance()->$var;
 
   }
 
   
    public 
function is_logged_in()
 
   {
 
       return true;
 
   }


And the model Users_model.php with the following code:
PHP Code:
defined('BASEPATH') OR exit('No direct script access allowed');

class 
Users_model extends CI_Model
{
    public function 
__construct()
    {
        
parent::__construct();
    }

    public function 
login_remembered_user()
    {
        
$cookie_id $this->user->cookie_prefix 'id';
        
$cookie_rc $this->user->cookie_prefix 'rc';

        if(
$this->user->is_logged_in() && get_cookie($cookie_id) && get_cookie($cookie_rc))
        {
            
        }
    }


The problem is that in the model at method login_remembered_user i get the error that class user isn't set, although the user library is autoloaded...

What i'm doing wrong?
As I know $this  in library does not reference to CI, it references library class itself.


Thus in your code
$this->load within library

you need to get instance of CI
so instead of:

Code:
 $this->load->model('users_model');
try:

Quote:
PHP Code:
$CI =& get_instance();
$CI->load->model('user_model');

$CI->users_model->login_remembered_user(); 
(04-21-2017, 04:34 AM)neuron Wrote: [ -> ]As I know $this  in library does not reference to CI, it references library class itself.


Thus in your code
$this->load within library

you need to get instance of CI
so instead of:

Code:
 $this->load->model('users_model');
try:

Quote:
PHP Code:
$CI =& get_instance();
$CI->load->model('user_model');

$CI->users_model->login_remembered_user(); 

For this in the user library is the following method:
PHP Code:
public function __get($var)
    {
        return 
get_instance()->$var;
    }