【问题标题】:Is there a way to define an alias for static class method?有没有办法为静态类方法定义别名?
【发布时间】:2012-07-30 12:58:01
【问题描述】:

基本上我的问题如标题所述......

我想让用户能够为类中的静态方法定义别名(在我的例子中,专门为 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');  

此外,如果我可能没有考虑过我的方法中的任何优点或缺点,请随时发表评论。我了解这种方法存在一些风险,例如,别名变量可能在用户定义后被覆盖。

【问题讨论】:

    标签: php alias static-methods


    【解决方案1】:

    也许你可以利用__callStatic“魔法”方法。详情请见here

    不过,我不确定您打算如何在别名和实际静态方法之间进行映射。也许您可以有一个配置 XML,您可以在其中指定映射,并在此基础上使用 __callStatic 将调用转发到真实方法。

    【讨论】:

    • 很酷的方法...这样做以及使用 class_alias 为类名取别名应该可以很好地工作。
    猜你喜欢
    • 2013-11-28
    • 2013-04-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多