PHP中的静态方法与非静态方法有什么区别吗? [英] Does static method in PHP have any difference with non-static method?

查看:293
本文介绍了PHP中的静态方法与非静态方法有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class t {
    public function tt()
    {
        echo 1;
    }
}
t::tt();

也可以在类级别调用非静态函数,所以如果在public之前添加static关键字又有什么不同呢?

See?The non-static function can also be called at class level.So what's different if I add a static keyword before public?

推荐答案

除此以外,如果您尝试在方法中使用$this,如下所示:

Except that, if you try to use $this in your method, like this :

class t {
    protected $a = 10;
    public function tt() {
        echo $this->a;
        echo 1;
    }
}
t::tt();

静态调用非静态方法时,会出现致命错误:

You'll get a Fatal Error when calling the non-static method statically :

Fatal error: Using $this when not in object context in ...\temp.php on line 11

即您的示例有点太简单了,并且与实际情况并不完全对应;-)

i.e. your example is a bit too simple, and doesn't really correspond to a real-case ;-)


另请注意,您的示例应向您发出严格警告(引用 ):


Also note that your example should get you a strict warning (quoting) :

静态调用非静态方法 生成E_STRICT级警告.

Calling non-static methods statically generates an E_STRICT level warning.

它实际上是(至少在PHP 5.3中如此):

Strict Standards: Non-static method t::tt() should not be called statically in ...\temp.php on line 12
1

所以:不是那么好;-)

So : not that good ;-)


不过,静态调用非静态方法看起来并不像任何一种好的作法((这可能是为什么它会发出严格警告)的原因,因为静态方法的含义与非静态方法不同-static方法:静态方法不引用任何对象,而非静态方法可在调用该类的实例上工作.


Still, statically calling a non-static method doesnt't look like any kind of good practice (which is probably why it raises a Strict warning), as static methods don't have the same meaning than non-static ones : static methods do not reference any object, while non-static methods work on the instance of the class there're called on.


再一次:即使PHP允许您做(也许是出于历史原因-例如与旧版本的兼容性),但这并不意味着您应该这样做!


Once again : even if PHP allows you to do something (Maybe for historical reasons -- like compatibility with old versions), it doesn't mean you should do it !

这篇关于PHP中的静态方法与非静态方法有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆