2

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!

Kevin Brown
  • 12,602
  • 34
  • 95
  • 155

4 Answers4

4

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!

Community
  • 1
  • 1
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
1

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.

Fer
  • 4,116
  • 16
  • 59
  • 102
0

You can use this method too inside your controller

function __construct() {
    // this is how you reference $id within the class
    DEFINE("userId",$this->session->userdata('id'));
}

And Call It As :

function getID() {
    // returning the $id property
    return userId;
}
Hamza
  • 11
  • 5
0

Define that very line in a constructor only

Koo5
  • 1