|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-08-22 21:19 UTC] matt dot minix at gmail dot com
Description:
------------
An anonymous function doesn't seem like it can be called directly when in a static
class.
Test script:
---------------
class a {
public static $b;
}
a::$b = static function($c) { echo $c; };
a::$b('Test');
I am however able to do
class a {
public static $b;
}
a::$b = static function($c) { echo $c; };
$Temp = a::$b;
$Temp('Test');
Expected result:
----------------
"Test"
Actual result:
--------------
Fatal error: Function name must be a string
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Dec 08 05:00:01 2025 UTC |
PHP behaves as reported. It does not work 5.5 also. [yohgaki@dev PHP-5.5]$ ./sapi/cli/php <?php class a { public static $b; } a::$b = static function($c) { echo $c; }; a::$b('Test') ?> Fatal error: Function name must be a string in - on line 7It's ambiguous at compile time: Does "Class::$foo()" 1. As requested: execute the function stored in/referenced by Class::$foo 2. As currently: execute the static method in Class named according to the local $foo 3. Another possibility: evaluate the static property of Class whose name is returned by $foo() The only way I see to support more than one would be to resolve it at runtime, but even then it's still possible to write something that is legal all three ways: <?php class Ambiguous { public static $one; public static function two() { echo "two"; } public static $three = 3; } Ambiguous::$one = function() { echo "one"; }; function two() { echo "three"; return "three"; } $one = "two"; // 1. call_user_func(Ambiguous::$one) // 2. call_user_func("Ambiguous::" . $one) // 3. Ambiguous::${$one()} Ambiguous::$one(); ?> Looking at just the last line I'm not even sure what *I* would expect it to do...Closing this as Won't Fix - I don't think this is going to change. As requinix pointed out the syntax is ambiguous and we're going with the "method call" interpretation. The same issue also exists with ordinary properties and it was decided against special casing this when the $this binding was implemented in PHP 5.4. In PHP 7 you can disambiguate this by writing (a::$b)('Test'). In PHP 5 you can write call_user_func(a::$b, 'Test').