Codeigniter: Set 'global variable'

2019-04-01 22:09发布

问题:

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!

回答1:

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!



回答2:

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.



回答3:

Define that very line in a constructor only



回答4:

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;
}