在 PHP 5.3 之前 const 關鍵字只能用於 CLASS 之內,但現在跟 define() 一樣可用於全局範圍。
define('APPLE', 'apple');
const ORANGE = 'orange';
echo APPLE;
echo ORANGE;
兩者有些差別,const 中的量不能為運算式,只接受純量資料型別(boolean, integer, float, string)
define('APPLE', 1 + 2);
const ORANGE = 1 + 2;
echo APPLE;
echo ORANGE; // 出錯誤
除此以外,const 在效能上較佳,在我的測試中約是兩倍之多。
PHP 還可透過 APC 的 apc_define_constants() 或 PECL 擴展 hidef 來定義常量。奇怪的是前者在測試中並沒有優勢,不知那裏的錯。而 Hidef 卻比其他三種要快上 2000 倍,估計效能跟記憶體速度成正比。但安裝設定不便,在小應用中,似乎是多此一舉。
可參考:
- http://www.php.net/manual/en/language.constants.syntax.php
- http://stackoverflow.com/questions/2447791/define-vs-const

寫下您的回覆