Reputation: 125
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
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
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