I'm using PHP 7.1.11 on my machine.
Consider below working code :
<?php
class Foo {
public $bar;
public function __construct() {
$this->bar = function() {
return 42;
};
}
}
$obj = new Foo();
// as of PHP 7.0.0:
echo ($obj->bar)(), PHP_EOL;
?>
You can see that the anonymous function has been assigned to the class property bar
but this has been done in a constructor.
Can I define the same anonymous function outside the constructor or any other method i.e. at the type of property declaration itself and can call it from within any class method using $this
?
I tried below code but I got Fatal Error in output :
<?php
class Foo {
public $bar = function() {
return 42;
};
public function __construct() {
$this->bar();
}
}
$obj = new Foo();
//as of PHP 7.0.0:
echo $obj->bar, PHP_EOL;
?>
Output :
Fatal error: Constant expression contains invalid operations
I want the same output as working code 42