计算机网络/计算机科学与应用/系统/运维/开发

PHP 静态调用非静态方法


在类中,方法分为静态方法和非静态方法

class test{     
    function test(){         
        echo 'it works';     
    } 
} // Fatal error: Non-static method test::test() cannot be called statically in test::test();

这样访问,报错,方法名与类名相同是构造方法

那我们继续改造一下

class test{     
        function test(){         
            echo 'it works';     
        }     
        
        function test2(){         
            echo 'it works two';     
        } 
} //可以输出 但还是标准错误 //Strict Standards: Non-static method test::test2() should not be called statically in //it works two test::test2();


可以看到可以输出内容 但还是报标准错误

那么结论如下:不推荐使用className::classMethod() 方式调用非静态方法


<?php  
class test{     
    function test(){         
        echo 'it works';     
    }     
    
    function test2(){         
        echo 'it works two';     
    }     
    
    static function test3(){         
        echo 'it works three';     
    } 
}

调用静态方法

test::test3();



PHP

无才无以立足,不苦不能成才。

评论

^