Month: June 2014

PHP var keyword

這幾天再複習PHP OOP的觀念,有一個我覺得怪怪的地方,就是PHP 宣告class member variable的方法一開始我看的書是說用var keyword,而且用var來宣告member variable預設的Property Visibility是public,但是書本後面又說宣告member variable也可以用public private protected,但我不懂這兩種方法差在哪裡?後來去翻了一下PHP Manual,解解惑~


A class is a collection of variables and functions working with these variables. Variables are defined by var and functions by function. A class is defined using the following syntax:


Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.

Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

總結:在PHP4宣告member variable得用var keyword,但是在PHP5可以使用public private protected這些keyword,所以已經可以不必再使用var keyword,雖然在PHP5還是有相容這部分,但如果考慮到程式碼的嚴謹性,盡量避免使用比較好。