0

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?

  • 1
    You can't call a class from inside a class you either need to extend `Baz` or pass `Baz` through `Foo`s construct to use `Baz` as a variable – Matt Jul 07 '16 at 08:57
  • 3
    http://stackoverflow.com/questions/9009276/php-object-assignment-to-static-property-is-it-illegal – RomanPerekhrest Jul 07 '16 at 08:58

2 Answers2

3

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";
    }
}
André Ferraz
  • 1,511
  • 11
  • 29
1

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
  }

}
?>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109