在php中define()與const()都可以定義常量,那么define()與const的區別到底在哪里呢,這個很多程序員都不明白,下面我給大家介紹一些關于此函數用法比對吧。
define()與const的區別:
define() 在執行期定義常量,而 const 在編譯期定義常量。這樣 const 就有輕微的速度優勢(即性能稍微好點),但不值得考慮這個問題,除非你在構建大高并發系統。
define() 將常量放入全局作用域,即使在命名空間中使用define方法定義常量也屬于全局作用域的。不能使用 define() 定義類常量(類常量使用const定義),命名空間作用域內的常量使用const定義如: namespace const ABC=’100′;。
define() 允許你在常量名和常量值中使用表達式,而 const 則都不允許。 這使得 define() 更加靈活。
define() 可以在 if() 代碼塊中調用,但 const 不行,在同一作用域下,define()常量名和const定義的常量名不能相同,const可以定義類常量和命名空間常量.如
namespace abc; const ABC = ‘a’; class hello { const C_NUM = 8; }
代碼如下:
- if (...) {
- const FOO = 'BAR'; // invalid
- }
- but
- if (...) {
- define('FOO', 'BAR'); // valid
- }
const采用一個普通的常量名稱,define可以采用表達式作為名稱,代碼如下:
- const FOO = 'BAR';
- for ($i = 0; $i < 32; ++$i) {
- define('BIT_' . $i, 1 << $i);
- }
const只能接受靜態的標量,而define可以采用任何表達式,代碼如下:
- const BIT_5 = 1 << 5; // invalid
- but
- define('BIT_5', 1 << 5); // valid
const 總是大小寫敏感,然而define()可以通過第三個參數來定義大小寫不敏感的常量,代碼如下:
- define('FOO', 'BAR', true);
- echo FOO; // BAR
- echo foo; // BAR
總結:使用const簡單易讀,它本身是一個語言結構,而define是一個方法,用const定義在編譯時比define快很多。
新聞熱點
疑難解答