2012-07-30 176 views
3

基本上我的问题是如标题中所述...有没有办法为静态类方法定义别名?

我想让用户能够为类中的静态方法(在我的情况下专门为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'); 

此外,随时在我的方法,我还没有考虑任何优点或缺点发表评论。我知道这种方法存在一些风险,例如,在用户定义它之后可以覆盖别名变量。

回答

5

也许你可以利用__callStatic“魔法”的方法。详细信息请参见here

虽然我不确定您是如何计划在别名和实际静态方法之间进行映射的。也许你可以在你指定映射的地方有一个配置XML,然后你可以基于此来调用实际方法__callStatic

+0

很酷的方法...做到这一点,使用class_alias别名类名应该工作得很好。 – br3nt 2012-07-30 13:09:36

相关问题