dongzhengzhong1282 2014-02-08 11:07
浏览 63
已采纳

PHP闭包作为静态类变量

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条回答 默认 最新

  • douyong1886 2014-02-08 11:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用