php中const與define的使用區別 詳解

一、const用於類成員變量定義,一旦定義且不能改變其值。define定義全局常量,在任何地方均可以訪問。 編譯

二、define不能在類中定義而const能夠。
 
三、const不能在條件語句中定義常量

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);  www.2cto.com
echo FOO; // BAR 
echo foo; // BAR 
總結:
使用const簡單易讀,它自己是一個語言結構,而define是一個方法,用const定義在編譯時比define快不少。 co

相關文章
相關標籤/搜索