dongshuo9350 2014-04-01 14:12
浏览 30
已采纳

具有普通和静态接口的类

I need a class that would let the user take advantage of both normal (non-static) methods and static methods. The actual implementation would reside in the static methods, which would be called by virtual non-static methods of the same name via the magic __call method. The problem however is that, when calling a non-static method in this way, PHP thinks that the programmer made a mistake and the static method was actually meant to be called:

class AClass
{
    public static function method ()
    {
        // implementation
    }

    public function __call ($name, $arguments)
    {
        var_dump("Hello");
        call_user_func_array("AClass::$name", $arguments);
    }
}

$obj = new AClass;
$obj->method();

So "Hello" is no being output when invoking method method on the object but is being output if trying to invoke a method with any other name. Any way to achieve the correct behavior while preserving method naming?

  • 写回答

1条回答 默认 最新

  • doumeng1143 2014-04-01 14:27
    关注

    I don't really see why you would try to do that but this seems to work :

    class AClass
    {
        protected static function method ()
        {
            echo "method()
    ";
        }
    
        public function __call ($name, $arguments)
        {
            echo("Hello normal
    ");
            call_user_func_array("self::$name", $arguments);
        }
    
        public static function __callStatic($name, $arguments)
        {
            echo("Hello static
    ");
            call_user_func_array("self::$name", $arguments);
        }
    }
    
    $obj = new AClass;
    
    // Normal call
    $obj->method();
    
    // Static call
    AClass::method();
    

    Output :

    Hello normal
    method()
    Hello static
    method()
    

    The thing is, accordingly to its documentation, the __call method is only used if a function is inaccessible from the context you called it from.

    So since in your case the function was public, there was no need to use it (even if with some settings it displays a warning).

    If you make it "protected" or "private", it can't be called from the outside and then __call is used.

    Because __call doesn't care about static calls, you also have to use __callStatic (available in PHP >=5.3) if you still need to call AClass::method from outside your class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?