首页 > Web开发 > 详细

php中const与define的使用区别 详解

时间:2014-10-30 18:45:23      阅读:230      评论:0      收藏:0      [点我收藏+]

1、const用于类成员变量定义,一旦定义且不能改变其值。define定义全局常量,在任何地方都可以访问。

2、define不能在类中定义而const可以。
 
3、const不能在条件语句中定义常量

if (...) { 
    const FOO = ‘BAR‘;    // invalid 

 
but 
 
if (...) { 
    define(‘FOO‘, ‘BAR‘); // valid 

4、const采用一个普通的常量名称,define可以采用表达式作为名称。


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

5、const只能接受静态的标量,而define可以采用任何表达式。

const BIT_5 = 1 << 5;    // invalid 
 
but 
 
define(‘BIT_5‘, 1 << 5); // valid 

6、const 总是大小写敏感,然而define()可以通过第三个参数来定义大小写不敏感的常量

define(‘FOO‘, ‘BAR‘, true);  www.2cto.com
echo FOO; // BAR 
echo foo; // BAR 
总结:
使用const简单易读,它本身是一个语言结构,而define是一个方法,用const定义在编译时比define快很多。

php中const与define的使用区别 详解

原文:http://www.cnblogs.com/walter371/p/4063303.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!