Search code examples
phpparse-error

Set an objects property equal to an instance of another object


Possible Duplicate:
Initializing PHP class property declarations with simple expressions yields syntax error

I dont want to have to instantiate my session object in every method. Why cant I do this:

class Foo {

   public $session = Session::instance();

   public function bar() {
      // Pass success message in session
      $this->session('message', 'Success');

   }
}

The error I get:

[ Parse Error ]: syntax error, unexpected '(', expecting ',' or ';'

Solution

  • PHP doesn't allow you to use expressions in class definitions (which is standard in class definitions in many languages). You can do a couple of things:

    public function __construct() {
       $this->session = Session::instance();
    }
    
    //Dependency Injection
    public function __construct(Session $session) {
       $this->session = $session;
    }