通过 isset() 后立即未定义的私有静态变量

Private static variable undefined immediately after passing isset()

我 运行 遇到了一个非常奇怪的问题,我在通过 isset() 调用后立即抛出 Undefined variable: authenticated_function 异常。代码:

class AuthService
{
    static $authenticated_function;

    public static function setAuthenticatedFunction($func)
    {
        \Log::info("Function Set");
        self::$authenticated_function = $func;
    }

    public function authenticated()
    {
        \Log::info("ISSET: " . isset(self::$authenticated_function));
        var_dump(self::$authenticated_function);
        if(isset(self::$authenticated_function))
            self::$authenticated_function(); //Exception is thrown here
    }
}

在我的日志文件中:

[2016-12-19 19:05:08] local.INFO: Function Set  
[2016-12-19 19:05:08] local.INFO: ISSET: 1

var_dump():

object(Closure)[103]
  public 'this' => 
    object(App\Providers\AppServiceProvider)[86]
      ... //Removed for brevity
  protected 'defer' => boolean false

PHP 7.0.8

Laravel 5.3

你有这个错误,因为 PHP 尝试像这样执行你的指令:

self:: + [ $authenticated_function + () ]

所以,你的变量不存在... Undefined variable: authenticated_function

如果要执行函数,可以这样使用:

$func = self::$authenticated_function;
$func();

或更好:

call_user_func(self::$authenticated_function /*, $param1, $param2*/);
// or
call_user_func_array(self::$authenticated_function /*, [$param1, $param2]*/);

:)