define VS const

php定義常量的方式有兩種defineconst,二者有什麼區別?php

const CONSTANCE = 'const';
define('CONSTANCE',  'const');

const關鍵字從php 5.3之後能夠在類定義以外定義常量

const能夠在類內部定義,而define不行。
const定義的常量在當前的命名空間中,而define要定義執行的命名空間,必須寫出具體命名空間。數組

class Foo {
    const BAR = 2;
}


class Foo2 {
    define("BAR", 3); //無效的
}

//命名空間的示例
namespace A{
    const A1 = 1; //處在命名空間A中
    define('A2',  2); //全局可調用
    define('A\A3', 3); //處在命名空間A中
}

namespace B{
    use const \A\A1;
    use const \A\A3;
    
    echo A1;
    echo A2; //全局調用
    echo A3;
}

const是在編譯階段定義常量,define是在預處理階段定義常量

const在編譯階段就定義了常量,定義常量時必須處於最頂端的做用區域。
因此不能再if等條件語句中定義。spa

define定義常量,又叫宏定義,能夠描述爲根據一系列預約義的規則替換必定的文本模式。
define能夠在分支中存在。code

理論上,使用const處理速度比define會快一點點。ip

const只接受標量數據,(如integer, string, boolean和float等);define能夠接受任意表達式

define('BIT_5',   1<<5); 
const BIT_5 =     1<<5; //5.6以後纔有效
從php 5.6起, const也能夠接受數組和表達式
define能夠接受 resource類型, const不行

const常量名只能是簡單字符,define能夠是任意表達式

const STR = 'string';
$i = 1;
define("STR_" . $i,  STR);
  1. const大小寫敏感,define能夠經過第三個傳參控制大小寫敏感。

另外幾個問題

  1. constdefine定義的常量數組是否能改變其中的元素?
  2. 可否用defined來檢查const定義的常量?
define vs const
相關文章
相關標籤/搜索