I wanted to have a static closure variable in my class, so that people can change the behavior of a specific part of the code. However, I can't seem to be able to initialize it anywhere.
First I tried this:
public static $logger = function($sql) { print_r($sql); };
But apparently PHP can't handle that. Ok, so I made a static init method:
public static $logger;
static function init() {
/* if (!Base::logger) */
Base::logger = function($sql) { print_r($sql); };
}
And call it at the end of the file, outside class definition. But this also give me a syntax error: Parse error: syntax error, unexpected '=' in [file] on line [line]. Any hints?
The syntax error is right where the error message tells you it is (it would have been even easier to spot if you had given us line numbers...): a missing
$
-sign.In addition to that, you migth want to use
self::
instead ofBase::
, this ensure the code will work without any additional changes if you ever rename the classYou can improve this code even further, when changing the initializer to a getter that JIT-creates the closure:
[Edit] Based on your comment on this: the clean OOP way of being able to change $logger would be to use a setter:
COmbining this and the getter from above ensures that you always get the value set by the setter, and, if none has been set yet, the default value. Using the setter to set the value back to
NULL
makes the getter create the default again, which is anoth er plus.