php 方法别名,php – 有没有办法为静态类方法定义别名?

基本上我的问题如标题中所述……

我想让用户能够为类中的静态方法定义别名(在我的情况下专门针对MyClass).

我没有找到类似于class_alias的任何功能.当然,用户可以定义自己的函数来调用静态方法来实现这个目标……但是还有其他/更好/更简单/不同的方法吗?

这是我到目前为止的尝试……

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“魔术”方法.有关详情,请参见here.

但是我不确定你打算如何在别名和实际的静态方法之间进行映射.也许您可以使用配置XML来指定映射,然后使用__callStatic将调用转发给实际方法.

标签:php,alias,static-methods

来源: https://codeday.me/bug/20190901/1786913.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值