PHP 中新增 const 常量与 define 的异同
该文章迁移自作者的旧博客站点。
源地址:http://fenying.blog.163.com/blog/static/102055993201505105511461/。
源地址:http://fenying.blog.163.com/blog/static/102055993201505105511461/。
PHP 5.3 中新增了 const
关键词用于定义常量,本文介绍其与 define
直接的区别。
const
关键词用法如下:
const XXX = 1;
这样的常量定义语法,虽然说他可以和define 一样用,但总归是不同的,不同之处如下:
1. namespace 绑定
define
定义的常量默认不受 namespace
约束,是全局常量,而 const
则受 namespace
严格约束,为局部常量,可以参考如下代码:
<?php
namespace A;
define('dddd', 234); # define dddd 1
const dddd = 4444; # define dddd 2
namespace A\B;
echo dddd, '<br>'; /* echo dddd.1*/
const dddd = 123; # define dddd 3
echo dddd, '<br>'; /* echo dddd.3*/
namespace B;
echo dddd, '<br>'; /* echo dddd.1*/
echo \A\dddd, '<br>'; /* echo dddd.2*/
echo \A\B\dddd, '<br>'; /* echo dddd.3*/
实际上也可用
define('A\B\C', 213);
定义特定命名空间下的常量。
2. const 只能接受字面量
define
可以接受任何结果为数值、字符串型的表达式,而 const
只能用字面量,参考如下:
<?php
define('ddd', strlen('ddd')); /*OK*/
define('abc', 111 * 3333); /*OK*/
const abc = 123; /*OK*/
const abc = 'ffff'; /*OK*/
const abc = strlen('ddd'); /* FORGET IT, NO WAY */
const abc = 123 * 44433; /* FORGET IT, NO WAY */
3. const 是静态常量
const 生效在编译阶段,不能在执行过程中根据条件定义 const 常量,而 define 可以,因为后者是函数,参考如下:
<?php
if (1 < 5) {
define('ddd', 123);
}
if (5 > 3) {
const kkk = 321; /* NO WAY */
}
4. define 允许大小写不敏感的常量名
<?php
define('ddd', 123, true);
echo DdD;
const kkk = 555;
echo kKk; # WHAT IS kKk?
归纳了这几点,使用 const 时千万注意了,如果还有别的我会继续补充。
comments powered by Disqus