Everyone knows that define defines constants. What if we define constants in a class? Of course, you cannot use define, but use const, as in the following example:
<?php //在类外面通常这样定义常量 define("PHP","phpernote.com"); class MyClass{ //常量的值将始终保持不变。在定义和使用常量的时候不需要使用$符号 const constant = 'constant value'; function showConstant() { echo self::constant; } } echo MyClass::constant; $classname = "MyClass"; echo $classname::constant; // PHP 5.3.0之后 $class = new MyClass(); $class->showConstant(); echo $class::constant; // PHP 5.3.0之后 print_r(get_defined_constants()); //可以用get_defined_constants()获取所有定义的常量
Generally, define defines constants outside the class, const defines constants within the class, and const must be accessed through class name::variable name. However, php5.3 and above support defining constants through const outside the class. As shown below, this is ok:
const a = "abcdef"; echo a;
I won’t go into the basic knowledge about constants here. In addition to the above, there are other differences between define and const (excerpted from Network):
1.const cannot define constants in conditional statements, but define can, as follows:
if(1){ const a = 'java'; } echo a; //必错
2.const uses an ordinary constant name, and define can use expressions As a name
const FOO = 'PHP'; for ($i = 0; $i < 32; ++$i) { define('PHP_' . $i, 1 << $i); }
3.const can only accept static scalars, while define can take any expression.
const PHP = 1 << 5; // 错误 define('PHP', 1 << 5); // 正确
4.const itself is a language structure. And define is a function. So using const is much faster.
That’s all about the difference between const and define in php.
The above is the detailed content of What is the reason why php uses const error?. For more information, please follow other related articles on the PHP Chinese website!