Welcome Guest, Not a member yet? Register   Sign In
When to use get_instance
#1

[eluser]vertmonkee[/eluser]
I am just looking at creating my own library. I believe there are authentication libraries avilable but I'm keen to use this as a first try of writing my own library.

The question I have is about when to use get_instance, if I have a class as follows

Code:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//Library to deal with all authentication
class Authentication {
    
    function Authentication() {

    }
    
    //Function to check users login credentials
    function login($email, $password) {
             //Check DB for user auth
    }
    
    //Function to check that a user is currently logged in
    function loggedInCheck() {
        
        $obj =& get_instance();
        return $obj->session->userdata("session_id");
        
    }
    
    //Function to logout a user
    function logout() {
         //Destroy the current session
    }
    
}

Do I have to use get_instance in all of my methods or can I just include it once and have all methods access it? If so hwo do I acheive this?

Thanks for any help
#2

[eluser]danmontgomery[/eluser]
The instance is returned, not declared globally, so you can only use it in the scope which it's called. If you want to use it throughout the class, declare it in the constructor as a class member.

Code:
class Authentication {
  function Authentication() {
    $this->obj =& get_instance();
  }

  function loggedInCheck() {
    return $this->obj->session->userdata("session_id");
  }
}

Or, you can define it locally in each method you want to use it, like in your example.
#3

[eluser]vertmonkee[/eluser]
Wow thanks for your super quick reply.

That has completley cleared that up for me.

Thanks very much.




Theme © iAndrew 2016 - Forum software by © MyBB