PHP常量的定义和用法,define和const

174次阅读
没有评论

原链接:https://www.cnblogs.com/xiaozhang666/p/11027613.html

define 和 const 有什么区别

1、const 是一个语言结构;而 define 是一个函数,可以通过第三个参数来指定是否区分大小写。true 表示大小写不敏感,默认为 false

define('PI', 3.14, true);

2、const 简单易读,编译时要比 define 快很多。

3、const 可在类中使用,用于类成员常量定义,定义后不可修改;define 不能在类中使用,可用于全局变量

class MyClass
{
    const CONS = '常量值';

    function showConstant() {
        echo  self::CONS . PHP_EOL;
        echo  constant('CONS');      
    }
}

4、const 是在编译时定义,因此必须处于最顶端的作用区域,不能在函数,循环及 if 条件中使用;而 define 是函数,也就是能调用函数的地方都可以使用

if (...){const FOO = 'BAR';    // 无效的 invalid}
if (...) {define('FOO', 'BAR'); // 有效的 valid
}

5、const 只能用普通的常量名,define 常量名中可以有表达式

const  FOO = 'BAR';
for ($i = 0; $i < 32; ++$i) {define('BIT_' . $i, 1 << $i);
}

6、const 定义的常量只能是静态常量,define 可以是任意表达式

const BIT_5 = 1 << 5;    // valid since PHP 5.6
define('BIT_5', 1 << 5); // 有效的 valid
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码