当前位置:Gxlcms > PHP教程 > php中const与define的区别分析

php中const与define的区别分析

时间:2021-07-01 10:21:17 帮助过:14人阅读

  1. if (...) {
  2. const FOO = 'BAR'; // invalid
  3. }
  4. but
  5. if (...) {
  6. define('FOO', 'BAR'); // valid
  7. }

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

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

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

  1. const BIT_5 = 1 << 5; // invalid
  2. but
  3. define('BIT_5', 1 << 5); // valid

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

  1. define('FOO', 'BAR', true);
  2. echo FOO; // BAR
  3. echo foo; // BAR

由以上的示例,我们得出,const简单易读,它本身是一个语言结构,而define是一个方法,用const定义在编译时比define快很多。 至于用哪个,根据自己的需要来吧。

人气教程排行