加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 何时需要使用静态方法?

发布时间:2020-12-13 17:45:34 所属栏目:PHP教程 来源:网络整理
导读:我认为通常我们使用静态方法,因为我们不需要实例化对象.我们可以使用className :: staticFunction来调用静态方法,今天发现了: test1.php ?phpclass Foo { static public function helloWorld() { print "Hello world " ; }}Foo::helloWorld(); test2.php ?p
我认为通常我们使用静态方法,因为我们不需要实例化对象.我们可以使用className :: staticFunction来调用静态方法,今天发现了:

test1.php

<?php
class Foo { 
    static public function helloWorld() {
        print "Hello world " ;
    }
}
Foo::helloWorld();

test2.php

<?php
class Foo { 
    public function helloWorld() {
        print "Hello world " ;
    }
}
Foo::helloWorld();

题:

以上两个脚本都有效.我们没有将函数声明为static,我们仍然可以使用className :: staticFunction来调用函数.为什么我们需要使用静态方法?

解决方法

We did not declare function as static,we can still use className::staticFunction

您可能没有注意到的是PHP抱怨第二种类型的调用:

PHP Strict Standards: Non-static method Foo::helloWorld() should not be called statically in php shell code on line 1

Strict Standards: Non-static method Foo::helloWorld() should not be called statically in php shell code on line 1

要使这些通知可见,您需要使用ini_set()或通过php.ini配置文件将值error_reporting设置为-1;顺便说一句,在开发过程中建议这样做.

结论

静态调用的函数应声明为静态函数xyz().

更新

顺便说一句,使用范围解析运算符::并不一定意味着你正在进行静态调用;考虑这个例子:

class Foo 
{ 
    public function helloWorld() 
    {
        print "Hello world ";
    }

    public function doSomething()
    {
        self::helloWorld();
    }
}

$f = new Foo;
$f->doSomething();

这是因为使用self ::而不是Foo ::不会更改调用“mode”(除非您调用的方法被定义为static).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读