Specific to PHP 5.3.x
First off, it's not possible to assign lambdas as default property values (lambdas are not considered a constant expression). So it is not possible to make that assignment directly; you would need to do it inside the constructor.
Secondly, in PHP 5.3.x you cannot use $this
inside a lambda. The typical workaround is to make a copy of $this
and capture that, as in:
$that = $this;
$func = function() use($that) { ... };
However this way it's not possible to access non-public members of $that
from inside the lambda at all, so the technique cannot be used directly in your case.
What you should probably do is store $this->backend
in a local variable inside the constructor and use
that variable inside the lambda. Both the store and the capture can be done by value or by reference, depending on if you want any modifications to propagate outside the lambda and the possibility that the value of $this->backend
may change before the lambda is invoked:
public function __construct() {
$backend = $this->backend;
$this->commands = array(
'say' => function($msg) use($backend) { fwrite($backend, $msg); }
);
}
Later PHP versions
Starting from PHP 5.4.0 you can implicitly use $this
inside a lambda defined within a class method:
public function __construct() {
$this->commands = array(
'say' => function($msg) { fwrite($this->backend, $msg); }
);
}
The restriction that lambdas cannot be assigned as default property values still stands.