views:

26

answers:

3

If I want to set a variable that my whole controller can access, how do I do it?

Right now, in every function I am setting

$id = $this->session->userdata('id');

I'd like to be able to access $id from any function w/o defining it for each controller. :)

If there's a better way, I'm all ears! I'm a noob!

A: 

Define that very line in a constructor only

Koo5
I get "Undefined variable". Could you give more information?
Kevin Brown
A: 

To elaborate on Koo5's response, you'll want to do something like this:

class yourController extends Controller {

    // this is a property, accessible from any function in this class
    public $id = null;

    // this is the constructor (mentioned by Koo5)
    function __construct() {
        // this is how you reference $id within the class
        $this->id = $this->session->userdata('id');
    }

    function getID() {
        // returning the $id property
        return $this->id;
    }

}

See the manual for more information on PHP properties and constructors. Hope that helps!

Colin
You saved me again, Colin. Thanks!
Kevin Brown
Glad I could help, Kevin!
Colin
+1  A: 

If with global you mean the scope of a single controller, the above answers are correct. If you want to access variables from multiple controllers, I recommend defining a BaseController class and then extending your normal controllers to inherit from that BaseController:

class yourController extends BaseController {}

I use this all the time for both global variables and methods.

Ferdy