Calling function variables with static variables

Approach 1 will work, but approach 2 will not - it will lead to a fatal error (the function name must be a string in ...)

# Approach 1 $function = self::$function and $function(); # Approach 2 self::$function and self::$function(); 

Isn't that weird? Hope someone can explain.


Edit: To give some context, here is a whole class:

 class Example { static $function; static function method() { self::$function(); } } function callback() {} Example::$function = 'callback'; Example::method(); 
+4
source share
3 answers

If you don't want to go into technical details about priority and ambiguity, a short explanation is that self::$function() works in the same way as $obj->$method() ; he is trying to call the variable function $function() self .

+1
source

The syntax seems ambiguous to me. This is probably also for PHP. It would be cleaner and more functional or save the function name in a local variable:

 static function method() $method = self::$function; $method(); } 

Or use call_user_func() :

 static function method() call_user_func(self::$function); } 
+1
source

Why approach number 1 works

This is a priority artifact of the PHP statement.

 $function = self::$function and $function(); 

equivalently

 ($function = self::$function) and $function(); 

which of course is equivalent

 $function = self::$function; if ($function) $function(); 

The last line works fine because the syntax is for variable functions .

Why approach number 2 does not work

Because there is ambiguity that the compiler resolves "in the wrong way."

Consider this:

 self::$function(); 

Does this mean that PHP should call the callback stored in the static $function property, or that it should call the static method whose name is the value of the $function variable?

PHP comes with the latter, but there is no $function variable in the area, leading first to a notification and then to an error ( $function evaluates to null , which is not a string).

+1
source

All Articles