V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Jaeger
V2EX  ›  PHP

关于 PHP 的 __callStatic 方法的一个大坑

  •  
  •   Jaeger · 2017-09-21 18:22:52 +08:00 · 4272 次点击
    这是一个创建于 2402 天前的主题,其中的信息可能已经有所发展或是发生改变。

    直接上代码:

    class A{
    	public static function __callStatic($name, $arguments)
    	{
    		echo $name.'静态方法不存在!';
    	}
    
    	public function test()
    	{
    		echo 'test 方法';
    	}
    }
    
    A::test();
    

    上面代码输出什么?

    结果调用了 test()方法,并没有执行__callStatic()方法,我的本意是想用__callStatic()处理A::test()这种错误的调用情况,这种情况该怎么处理呢?

    6 条回复    2017-09-30 12:21:41 +08:00
    gouchaoer
        1
    gouchaoer  
       2017-09-21 18:30:51 +08:00 via Android
    印象里有个 rfc 说这个,不过为了兼容社区不太可能改
    gouchaoer
        2
    gouchaoer  
       2017-09-21 18:32:00 +08:00 via Android
    java 里 object.staticMethod()也类似,都别改了
    wjfz
        3
    wjfz  
       2017-09-21 19:13:06 +08:00
    1、__callStatic 没有影响对 test 的调用,**只要**方法中没有$this 伪变量,就可以通过双冒号访问。
    只有当报错级别为 E_STRICT 时会报 warning,参考: http://php.net/manual/zh/language.oop5.basic.php

    2,__callStatic 的作用不是看方法存不存在,而是有没有“权限”访问到。

    > 在对象中调用一个不可访问方法时,__call() 会被调用。
    > 在静态上下文中调用一个不可访问方法时,__callStatic() 会被调用。
    参考: http://php.net/manual/zh/language.oop5.overloading.php#object.callstatic

    目标方法非 public 时__callStatic 才会起作用。




    ```php

    <?php
    class A{
    public static function __callStatic($name, $arguments)
    {
    echo "{$name}静态方法不存在!\n";
    }

    public function test()
    {
    echo "test 方法\n";
    }

    public static function test2()
    {
    echo "test2 方法\n";
    }

    private static function test3()
    {
    echo "test3 方法\n";
    }

    protected static function test4()
    {
    echo "test4 方法\n";
    }
    }

    A::test();
    A::test2();
    A::test3();
    A::test4();

    ```


    刚刚现查的,大神们要是看出什么错误记得指出。
    linxl
        4
    linxl  
       2017-09-22 10:25:36 +08:00
    php 手册里都说了 "当调用当前环境下未定义或不可见的类属性或方法时,重载方法会被调用。"
    你的 test() 是 public , 自然会被调用.
    http://php.net/manual/zh/language.oop5.overloading.php
    coooooooode
        5
    coooooooode  
       2017-09-22 12:10:39 +08:00
    照你这样说
    public function a();和 public static function a(); 可以同时存在?
    楼上说的对,我记得魔术方法是当你的方法名称不存在这个类中的时候才会调用。
    chemf
        6
    chemf  
       2017-09-30 12:21:41 +08:00
    PHP 是可以静态调用非静态方法的,5.3 之前的某个版本允许,之后的不建议使用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1010 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 500ms · UTC 18:58 · PVG 02:58 · LAX 11:58 · JFK 14:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.