工作中经常遇到使用php常量的情况,下面就define()和const的用法和区别做简要记录
区别
1,define()本身是一个函数,而const不是函数,它只是一个语句结构。因此const比define的编译速度要快很多。
2,define()不能在类中使用,const可以在类中使用。
3,define()能在条件语句中定义,const不可以。
4,define()可以采用表达式定义,const不可以。
使用
<?php
define('c1', 'c1');
const c2 = 'c2';
class test{
const c3 = 'c3';
public function t(){
echo self::c3;
}
}
$test = new test();
$test->t();
echo c1;
echo c2;
echo $test::c3;
?>
结果将输出
c3 c1 c2 c3