Home  >  Article  >  Backend Development  >  What is the reason why php uses const error?

What is the reason why php uses const error?

silencement
silencementOriginal
2019-09-27 15:44:352789browse

What is the reason why php uses const error?

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 = &#39;constant value&#39;;
    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 = &#39;java&#39;;
}
echo a;  //必错

2.const uses an ordinary constant name, and define can use expressions As a name

const  FOO = &#39;PHP&#39;;
for ($i = 0; $i < 32; ++$i) { 
    define(&#39;PHP_&#39; . $i, 1 << $i); 
}

3.const can only accept static scalars, while define can take any expression.

const PHP = 1 << 5;    // 错误
define(&#39;PHP&#39;, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn