2011-10-01 82 views
1

這是如何工作的?不應該這會拋出一個錯誤,因爲我試圖靜態調用一個非靜態方法?基本上,我從來沒有實例化一個類型的東西的對象。PHP靜態調用方法;即使其未定義爲靜態

class Something { 
    public function helloworld() { 
     echo 'hello world'; 
    } 
} 

Something::helloworld(); 
+0

沒什麼特別的,只是'$ this = null'。 –

+0

[PHP:通過ClassName ::方法語法調用實例方法,導致靜態調用?]的可能重複(http://stackoverflow.com/questions/4664511/php-call-to-an-instance-method -via-classnamemethod-syntax-results-in-a-static) – Gordon

回答

1

將這個在你的腳本的頂部:

error_reporting(E_ALL | E_STRICT); // E_STRICT is important here 
ini_set('display_errors', true); 

...看到那麼會發生什麼:

嚴格的標準:非靜態方法::東西的HelloWorld()不應該 可以在[...]

不可否認,它比一個錯誤的通知,雖然靜態調用。你的腳本將繼續愉快地繼續運行。

0

它只會給你一個錯誤,如果內helloworld()你會使用$this

這是一種由於缺少規格而導致的PHP「WTF」類型,它允許您靜態調用一個實際上沒有聲明的函數static

+0

IIRC,它不是一個丟失的規範,它只是向後兼容PHP 4. – hakre

+0

...沒有規格。 –

+0

嗯,它不是逐字寫出來的,但是如果你閱讀[PHP 5 docs](http://www.php.net/manual/en/language.oop5.static.php),那麼清楚地寫出未指定就像上市。而在PHP 4中,公共函數可以靜態調用。所以實際上它被記錄下來,甚至在靜態章節中。另請參閱:http://php.syntaxerrors.info/index.php?title=Call_to_undefined_function#NOTE:_Static_methods_in_PHP4 - 僅供參考,通常情況下,您不應該再關心PHP 4。 – hakre