References to static methods in PHP
Sep. 14th, 2012 01:21 pmAnother reason PHP sucks: references to static methods are not supported. There is a hacky way to use them, however.
Background: PHP handles function references as strings.
function myfunction($a) { ... }
$foo = "myfunction";
$foo("asdf"); // call myfunction("asdf");
That's weird, but fair enough. However, PHP falls apart when you try to call a static class method.
$func = MyClass::myfunction; // Undefined class constant myfunction [this is normal for PHP]
$func = "MyClass::myfunction"; // Call to undefined function MyClass::myfunction()
$func = "MyClass"::myfunction; // syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
$func = MyClass::"myfunction"; // syntax error, unexpected "myfunction"
// Given $prefix="MyClass" and $func="myfunction", attempting to create a reference produces:
$func = $prefix::$func; // Access to undeclared static property MyClass::$func
$func = MyClass::$func; // Access to undeclared static property: MyClass::$func
It seems to be a miracle that calling $prefix::$func() will work, but you cannot create a reference directly to it. Given that a passed-in function reference string $func may refer either to a static method or to a global function, we can do this:
$arr = array(); // "Only variables should be passed by reference" and offsets are undefined if this is not a separate line
preg_match("/(.*)::(.*)/", $func, $arr) ?
$arr[1]::$arr[2]("asdf")
: $func("asdf")
;
// You cannot (wrap) the ?: in parens, either. That is a syntax error.
This only works because PHP does not support subclasses, so the reference is guaranteed to never be more than one level deep.);
Edit: Just pass in an anonymous function reference wrapping the function that you want to call. That seems to work.
function($arg){ return MyClass::myfunction($arg); }
Edit: call_user_func("MyClass::myfunction", $arg1, ...) seems to work. The problem is when storing $func="MyClass::myfunction" and trying to call $func() directly.