1

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

Reaksmey
  • 205
  • 2
  • 7
  • 15
  • Default visibility of property is public. So you should explicitly declare visibility for `private $my_prefix;` before `__construct()` code shown in @thors1982 's answer. [Docs](http://php.net/manual/en/language.oop5.visibility.php#language.oop5.visiblity-methods). – Tpojka Oct 21 '16 at 23:01

1 Answers1

1

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

Community
  • 1
  • 1
thors1982
  • 36
  • 5
  • yes it work but i have 1 more question if declare `$this->my_prefix = $this->session->userdata('my_prefix'); ` in contruct do i need to declare `private $my_prefix = '';` is it necessary ? – Reaksmey Oct 21 '16 at 14:38
  • If you are using that variable outside of the constructor(which I assume you are) then yeah it is considered best practice to declare the private variable on the class. However you do not have to give it a default value of empty string you could also just do `private $my_prefix;` – thors1982 Oct 21 '16 at 14:43
  • The default value is pointless if it is populated by a constructor. – Narf Oct 21 '16 at 15:34