Search code examples
phplaravel-5.3php-7

Private static variable undefined immediately after passing isset()


I'm running into a really weird issue where I have an Undefined variable: authenticated_function exception being thrown immediately after passing an isset() call. Code:

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
    }
}

In my log file:

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

And the 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


Solution

  • You have this error, because PHP try to execute your instruction like this:

    self:: + [ $authenticated_function + () ]

    So, your variable does not exist ... Undefined variable: authenticated_function

    If you want to execute the function, you can use this way:

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

    or better:

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

    :)