剛剛發現的一個很奇怪的現象
下面這個數組我設定為類的屬性,其中SYSTEM_LIB為我定義的常量
final class Application { public static $_lib=array( 'route' => SYSTEM_LIB.'/lib_route.php', 'mysql' => SYSTEM_LIB.'/lib_mysql.php', );}
但最終運行時報錯為Parse error: syntax error, unexpected
而我將該數組放入方法中時,就能正常建立
final class Application { public static $_lib=array(); public static function run(){ self::$_lib =array( 'route' => SYSTEM_LIB.'/lib_route.php', 'mysql' => SYSTEM_LIB.'/lib_mysql.php', ); }}
我分析是因為當數組被設定為類屬性時,數組內的值必須在引號內,數組不認識常量
回複討論(解決方案)
類定義時,屬性不能賦予不確定的值
使用者常量是在程式運行時定義的
而語法檢查是在程式運行前進行的
而系統常量就是確定的值
class T { var $os = PHP_OS;}$p = new T;echo $p->os;
Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed.
與PHP的靜態變數一樣,靜態屬性只能使用一個字面值或常量來初始化(PHP5.6之前的版本);運算式是不允許的。
In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.
PHP5.6以上版本則與常量運算式的規則一樣,可以使用一些特定的運算式,只要其能在編譯時間被計算
所以你的第一種寫法在PHP5.6以上版本是可以正常啟動並執行。
印象中static靜態變數不能用其他變數或函數作為值初始化