基本上我的问题如标题所述。。。
我想让用户能够为类中的静态方法定义别名(在我的例子中,专门针对MyClass)。
我没有发现任何类似于class_alias的函数。当然,用户可以定义自己的函数来调用静态方法来实现这个目标。。。但是,还有其他/更好/更简单/不同的方法可以做到这一点吗?
这是我迄今为止的尝试。。。
<?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');
此外,请随意评论我的方法中任何我可能没有考虑过的优点或缺点。我知道这种方法有一些风险,例如,别名变量可能在用户定义后被覆盖。
也许您可以使用__callStatic
"magic"方法。请参阅此处了解详细信息。
不过,我不确定您计划如何在别名和实际静态方法之间进行映射。也许您可以有一个配置XML,在其中指定映射,并在此基础上使用__callStatic
将调用转发到实际方法。