I am using php 5.6, I want to do something like this:
class FooBar {
public function foo() {
echo "foo!";
array_map($this->bar, [1,2,3]);
}
private function bar() {
echo "bar!";
}
}
(new FooBar)->foo();
This gives the following error:
Notice: Undefined property: FooBar::$bar
Alternately, is it possible to declare an anonymous function as a class attribute? Something like this:
class FooBar {
private $bar = function() {
echo "bar!";
}
public function foo() {
echo "foo!";
array_map($this->bar, [1,2,3]);
}
}
(new FooBar)->foo();
This gives me the following error:
Parse error: syntax error, unexpected 'function' (T_FUNCTION)
I was able to get the result I was after with this:
class FooBar {
function __construct() {
$this->bar = function() {
echo "bar!";
};
}
private $bar;
public function foo() {
echo "foo!";
array_map($this->bar, [1,2,3]);
}
}
(new FooBar)->foo();
However this is less than ideal; I don't think those function definitions belong in the constructor - ideally I'd like to have them be static class methods.