I'm trying to declare a function and store it on a private static
field of my class. I've got something like this:
class MyClass {
private static $myFunction = function() { /* stuff here */ };
}
But I keep getting this error on the line that creates the function:
PHP Parse error: syntax error, unexpected 'function' (T_FUNCTION)…
I'm doing this based on this answer, as well as on what the PHP manual pages say. But it is not working for me. Why? what can I do?
The goal for all of this is that I could be able store the function on an array:
private static $options = [
'function' => MyClass::$myFunction
];
So what do you think is the best way to achieve this? I'm using PHP 5.5.14 in case you wonder.
Update:
I've tried a couple of different approaches. Like this:
class MyClass {
private static function myFunction() { /* Expression */ }
private static $options = [
'function' => MyClass::myFunction()
];
}
But it throws me errors about an unexpected '(':
PHP Parse error: syntax error, unexpected '(', expecting ']'…
And this. Which is the only one that works:
class MyClass {
private static function myFunction() { /* Expression */ }
public static function anotherFunction() {
$options = [ 'function' => MyClass::myFunction() ];
}
}
But I need to have this $options
var to be accessible to more methods on the same class, so it's not a solution.
I'd prefer to stay away from constructors, since it is only a helper class and I don't want to mess with instances of it and such things.