php const和define的区别

(1).const用于类成员变量的定义,一经定义,不可修改。define不可用于类成员变量的定义,可用于全局常量。
(2).const可在类中使用,php5.3以后类外边也可以,define不能。
class test {
   const  t002="t002";
   define(t001,"t001");//报错,不能这样使用
   function test(){
      define(t001,"t001");
      const  t002="t002";<span style="font-family: Arial, Helvetica, sans-serif;">//报错,不能这样使用</span>
   }
   function a() {
      echo t002;
   }
}
$t=new test();
$t->a();

输出:

Notice: Use of undefined constant t001 - assumed 't001' in D:\WWW\test\index.php on line 10

Notice: Use of undefined constant t002 - assumed 't002' in D:\WWW\test\index.php on line 13
t002
(3).const不能在条件语句中定义常量。
例如: 
if (...){ 
  const FOO = 'BAR';  // 无效的invalid 
}  

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  


define('BIT_5', 1 << 5); // 有效的valid
(6).const定义的常量时大小写敏感的,而define可通过第三个参数(为true表示大小写不敏感)来指定大小写是否敏感。
例如:
define('FOO', 'BAR', true);  
echo FOO; // BAR 
echo foo; // BAR

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值