2017-01-24 33 views
0

在PHP手冊它指出Scope Resolution Operator(::)有以下目的使用::爲非靜態方法?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

現在我只是碰到一個教程來了,是用雙冒號是這樣的:

class A { 
    public function nice(){ 
    echo "hi"; 
    } 
} 

$A = new A; 
A::nice(); 

和輸出實際上是

​​

但爲什麼這不會引發錯誤?函數nice不是一個靜態方法,也不是重寫該方法。像這樣使用雙冒號是不好的做法嗎?

+4

那是因爲你沒有啓用錯誤報告([DEMO](https://3v4l.org/5DVZI) )。恐怕有很多垃圾學習材料。 –

+1

反應還取決於PHP70中的PHP版本:「棄用:非靜態方法foo :: bar()不應該在' – JustOnUnderMillions

+0

@ÁlvaroGonzález中靜態調用。我實際上在sitepoint的書PHP Master中發現了這個問題。 – Adam

回答

3

它的工作原理與PHP 4的向後兼容性,如果你的錯誤報告是您將得到警告:

Strict Standards: Non-static method A::nice() should not be called statically

編輯其實你會得到最新版本的錯誤,而不是警告。

+0

http://stackoverflow.com/questions/4684454/error-message-strict-standards-non-static-method-should-not-be-called-staticall – TecBrat

1

它實際上返回棄用的通知,這是一個不好的做法:

PHP Deprecated: Non-static method A::nice() should not be called statically

它不會拋出一個錯誤,因爲它沒有引用$this,所以這種方法可以是靜態的反正。

如果你想嘗試引用$this,你會得到以下錯誤:

Fatal error: Uncaught Error: Using $this when not in object context