define和const這兩種方法之間的區別
- define() 在執行期定義常量,而 const 在編譯期定義常量。這樣 const 就有輕微的速度優勢, 但不值得考慮這個問題,除非你在構建大規模的軟件。
- define() 將常量放入全局作用域,雖然你可以在常量名中包含命名空間。 這意味着你不能使用 define() 定義類常量。
- define() 允許你在常量名和常量值中使用表達式,而 const 則都不允許。 這使得 define() 更加靈活。
- define() 可以在 if() 代碼塊中調用,但 const 不行。
<?php
// 來看看這兩種方法如何處理 namespaces
namespace MiddleEarth\Creatures\Dwarves;
const GIMLI_ID = 1;
define('MiddleEarth\Creatures\Elves\LEGOLAS_ID', 2);
echo(\MiddleEarth\Creatures\Dwarves\GIMLI_ID); // 1
echo(\MiddleEarth\Creatures\Elves\LEGOLAS_ID); // 2; 注意:我們使用了 define()
// Now let's declare some bit-shifted constants representing ways to enter Mordor.
define('TRANSPORT_METHOD_SNEAKING', 1 << 0); // OK!
const TRANSPORT_METHOD_WALKING = 1 << 1; //Compile error! const can't use expressions as values
// 接下來, 條件常量。
define('HOBBITS_FRODO_ID', 1);
if($isGoingToMordor){
define('TRANSPORT_METHOD', TRANSPORT_METHOD_SNEAKING); // OK!
const PARTY_LEADER_ID = HOBBITS_FRODO_ID // 編譯錯誤: const 不能用於 if 塊中
}
// 最後, 類常量
class OneRing{
const MELTING_POINT_DEGREES = 1000000; // OK!
define('SHOW_ELVISH_DEGREES', 200); // 編譯錯誤: 在類內不能使用 define()
}
?>