為什麼數組初始化時,賦值不能是常量?

來源:互聯網
上載者:User
剛剛發現的一個很奇怪的現象

下面這個數組我設定為類的屬性,其中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靜態變數不能用其他變數或函數作為值初始化

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.