Basically my question is as stated in the title…
I want to give users the ability to define an alias for the static methods in a class (in my case specifically for MyClass).
I haven’t found anything similar in function to class_alias. Sure, the user could just define their own function that calls the static method to achieve this goal… but are there other/better/simpler/different ways to do this?
Here is my attempt so far…
<?php
class MyClass {
/**
* Just another static method.
*/
public static function myStatic($name) {
echo "Im doing static things with $name :)";
}
/**
* Creates an alias for static methods in this class.
*
* @param $alias The alias for the static method
* @param $method The method being aliased
*/
public static function alias($alias, $method) {
$funcName = 'MyClass::'.$method; // TODO: dont define class name with string :p
if (is_callable($funcName)) {
$GLOBALS[$alias] = function() use ($funcName){
call_user_func_array($funcName, func_get_args());
};
}
else {
throw new Exception("No such static method: $funcName");
}
}
}
MyClass::alias('m', 'myStatic');
$m('br3nt');
Also, feel free to comment on any pros or cons in my approach that I may not have considered. I understand that there are some risks in this approach, such as, the aliased variable could be overridden after the user has defined it.
Perhaps you can make use of the
__callStatic“magic” method. See here for details.I’m not sure how you plan to map between the aliases and the actual static methods, though. Maybe you can have a configuration XML where you specify the mapping and you forward the calls to the real method with
__callStaticbased on that.