Nikolai Engel
Nikolai Engel

Reputation: 125

Expression not allowed - set class var with new object

I tried to do following stuff:

class Foo {
    private $bar = new baz(); // Expression is not allowed as field default value
}

class Baz {
    public function __construct() {
        echo "hello world";
    }
}

I cant find any results why the expression should not be allowed. Why can i assign string, integer and other data types but no objects?

Upvotes: 0

Views: 1186

Answers (2)

André Ferraz
André Ferraz

Reputation: 1521

Its just the way PHP works. You can't use functions (including constructors) in class properties.

The properties are a blueprint and must be independent of the runtime environment (source)

You can assign objects to the properties via the __construct()

class Foo {
    private $bar;

    public function __construct() {
         $this->bar = new baz();
    }
}

class Baz {
    public function __construct() {
        echo "hello world";
    }
}

Upvotes: 3

Niklesh Raut
Niklesh Raut

Reputation: 34924

This should work for you

<?php
class Baz {
    public function __construct() {
        echo "hello world";
    }
}
class Foo {
  private $bar;
  function __construct(){
    $bar = new Baz(); // Expression is not allowed as field default value
  }

}
?>

Upvotes: 1

Related Questions