2009年12月30日 星期三

php 物件的static method最好要以static keyword清楚標示

因為一時心血來潮  想知道呼叫php物件的 static method 跟 non-static method 在效率上有沒有差別
就寫了簡單的程式測試一下  一開始我的物件的method只有一個 並沒有以 static 關鍵字宣告:
class T
{
    public f()
    {
    }
}

而只是以兩種不同的方式呼叫:
1.
$o = new T();
$o->f();

2.
T::f();

結果以第二種方式 花的時間大概是 第一種方式的兩倍 讓我非常驚訝
後來我在php官網發現了造成效率差距這麼巨大的原因
Calling non-static methods statically generates an E_STRICT level warning.

即使在 php.ini 中的 error_reporting 設為 E_ALL 用第二種方式呼叫 method也不會出現 warning
因為 E_ALL 是不包含 E_STRICT 的  所以我便以為這樣寫的 code 是合法的 真是大錯特錯

我後來把 class 改寫:
class T
{
    public function f()
    {
    }

    public static function sf()
    {
    }
}

再以 T::sf() 呼叫 static method
結果是呼叫 static method 或是 non-static method 時間都差不多 感覺這樣才是合理的狀態

然後 我把 error_reporting 改成 E_ALL | E_STRICT 了
寫 code 還是要嚴謹一點才好