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

相关文章
相关标签/搜索