当前位置:Gxlcms > PHP教程 > php用const出错是什么原因

php用const出错是什么原因

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

大家都知道define是定义常量的,如果在类中定义常量呢?当然不能用define,而用const,如下例:

  1. <?php
  2. //在类外面通常这样定义常量
  3. define("PHP","phpernote.com");
  4. class MyClass{
  5. //常量的值将始终保持不变。在定义和使用常量的时候不需要使用$符号
  6. const constant = 'constant value';
  7. function showConstant() {
  8. echo self::constant;
  9. }
  10. }
  11. echo MyClass::constant;
  12. $classname = "MyClass";
  13. echo $classname::constant; // PHP 5.3.0之后
  14. $class = new MyClass();
  15. $class->showConstant();
  16. echo $class::constant; // PHP 5.3.0之后
  17. print_r(get_defined_constants()); //可以用get_defined_constants()获取所有定义的常量

一般是define在类外定义常量,const在类内定义常量,并且const必须通过类名::变量名来进行访问。但是php5.3以上支持类外通过const定义常量,看如下,这样是ok的:

  1. const a = "abcdef";
  2. echo a;

关于常量的基础知识,这里不说了,除了以上,define和const的其它区别(摘自网络):

1.const不能再条件语句中定义常量,但是define是可以的,如下:

  1. if(1){
  2. const a = 'java';
  3. }
  4. echo a; //必错

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

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

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

  1. const PHP = 1 << 5; // 错误
  2. define('PHP', 1 << 5); // 正确

4.const本身就是一个语言结构。而define是一个函数。所以使用const速度要快的多。

关于php中const和define的区别就总结这么多了。

以上就是php用const出错是什么原因的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行