大家都知道define是定义常量的,如果在类中定义常量呢?当然不能用define,而用const,如下例:
03 | define( "PHP" , "phpernote.com" ); |
06 | const constant = 'constant value' ; |
07 | function showConstant() { |
12 | echo MyClass::constant; |
14 | $classname = "MyClass" ; |
15 | echo $classname ::constant; |
17 | $class = new MyClass(); |
18 | $class ->showConstant(); |
19 | echo $class ::constant; |
21 | print_r(get_defined_constants()); |
一般是define在类外定义常量,const在类内定义常量,并且const必须通过类名::变量名来进行访问。但是php5.3以上支持类外通过const定义常量,看如下,这样是ok的:
关于常量的基础知识,这里不说了,除了以上,define和const的其它区别(摘自网络):
1.const不能再条件语句中定义常量,但是define是可以的,如下:
2.const采用一个普通的常量名称,define可以采用表达式作为名称
2 | for ( $i = 0; $i < 32; ++ $i ) { |
3 | define( 'PHP_' . $i , 1 << $i ); |
3.const只能接受静态的标量,而define可以采用任何表达式。
4.const本身就是一个语言结构。而define是一个函数。所以使用const速度要快的多。
关于php中const和define的区别就总结这么多了。