PHP closure as static class variable

两盒软妹~` 提交于 2019-12-25 06:57:59

问题


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?


回答1:


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.

Base::$logger = function (...)

In addition to that, you migth want to use self:: instead of Base::, this ensure the code will work without any additional changes if you ever rename the class

self::$logger = function (...)

You can improve this code even further, when changing the initializer to a getter that JIT-creates the closure:

private static $logger = NULL;

public static function getLogger () {
    if (self::$logger === NULL) {
        self::$logger = function ($sql) {print_r($sql);};
    }
    return self::$logger;
}

[Edit] Based on your comment on this: the clean OOP way of being able to change $logger would be to use a setter:

public static function setLogger ($closure) {
    self::$logger = $closure;
}

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.



来源:https://stackoverflow.com/questions/21645223/php-closure-as-static-class-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!