Home > php教程 > php手册 > body text

思绪凌乱了,原来非静态方法也可以静态调用(转),思绪静态

WBOY
Release: 2016-07-06 14:25:16
Original
1047 people have browsed it

思绪凌乱了,原来非静态方法也可以静态调用(转),思绪静态

1.PHP中可以静态调用非静态方法么?

今天我被问到PHP中可不可以使用 className::methodName() 的方法来调用一个没有声明Static的方法。在我的印象中,我好像是见过这种用法,但又有些不确定。大家都知道,在手册或者教程里,方法被分为静态方法和非静态方法,通常我们静态调用的方法,肯定是静态方法。

那如果我们调用了非静态方法会怎么样呢?首先做测试.
<?php <br /> class test{<br> function test(){<br> echo 'it works';<br> }<br> }<br> test::test();
执行以下,返回错误如下
Fatal error: Non-static method test::test() cannot be called statically in /home/×××/test.php<br> on line 7 Call Stack: 0.0002 332548 1. {main}() /home/×××/test.php:0
这个时候,可能大家就会认为静态调用非静态方法是行不通的了,但其实,结论下的过早了,因为test()这个方法比较特殊,与类同名,是构造方法。

我们继续测试。
<?php <br /> class test{<br> function test(){<br> echo 'it works';<br> }<br> function test2(){<br> echo 'it works too';<br> }<br> }<br> test::test2();
执行结果:
it works too
这说明,静态调用非静态方法是可行的,但是静态调用构造方法是不可以的。为了验证这个结论,我又做了如下测试:
<?php <br /> class test{<br> static function test(){<br> echo 'it works';<br> }<br> }<br> test::test();
执行的结果如下:
Fatal error: Constructor test::test() cannot be static in /home/xxx/test.php on line 9
构造方法不能声明静态,所以上面的推论正确。

但这个结果的确是很特殊的,因为可能只有PHP可以静态调用非静态方法,我用Java做了实验,如果静态调用非静态方法会报如下错误:
Cannot make a static reference to the non-static method showString() from the type HelloWorldApp
其他语言我没有一一尝试,但这已经足够来说明PHP的特殊之处,关于为什么PHP会有这样的情况我暂时没有找到相关说明。

2.静态调用非静态方法是否应该被应用?

那我们是不是可以使用这种方法来代替static方法呢? 首先在代码的可读性上来看,静态调用非静态方法当然是不被推荐的,这会让维护者产生疑惑。

接下来我们再做一些实验,来看一下静态调用非静态方法在效率上是否会有一定的优势。
<?php <br /> class test{function test2(){}}<br> for($k=0; $k {<br> test::test2();<br> }
上面代码在我这里的执行时间是18到28毫秒,我们再来测试标准的写法。
<?php <br /> class test{static function test2(){}}<br> for($k=0; $k {<br> test::test2();<br> }
上面的代码执行时间在5到10毫秒之间,这样看来,静态调用非静态方法的效率要比标准的静态方法调用低的多,所以在效率上也不推荐静态调用非静态方法

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!