Reaksmey
Reaksmey

Reputation: 205

Codeigniter how to declare private variable that get value from session_userdata in controller

i had problem that if i declare private variable getting session value by $this->session->userdata(). if just a nomol string it ok

private $table = 'contact'; // Work

private $my_prefix = $this->session->userdata('my_prefix'); 
// Error compile : Constant expression contains invalid operations

i had atleast 3 or more function in Controller and some of them need to get my_prefex session to do the job with difference language field in db. i don't want to declare $my_prefix = $this->session->userdata('my_prefix');in all Function i have in controller. is it possible to declare 1 private to use in all function of my controller. Thank in advance

Upvotes: 1

Views: 1237

Answers (1)

thors1982
thors1982

Reputation: 36

Expressions are not allowed as default values, which is also why you cannot set a property to a default value of 1+1 either, you would have to set it to 2. However you should be able to set the value in a constructor though. Try this

Class Foo {
    private $my_prefix = '';
    function __construct() {
        $this->my_prefix = $this->session->userdata('my_prefix'); 
    }
}

In the above code I am assuming the Foo object has access to codeigniters global $this object

For more information this stackoverflow page does a good job of explaining it Class - variable declaration

Upvotes: 1

Related Questions