What is the reason why php uses const error?

silencement
Release: 2023-02-25 10:12:01
Original
2602 people have browsed it

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:

showConstant();
echo $class::constant; // PHP 5.3.0之后

print_r(get_defined_constants()); //可以用get_defined_constants()获取所有定义的常量
Copy after login

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;
Copy after login

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;  //必错
Copy after login

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); 
}
Copy after login

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

const PHP = 1 << 5;    // 错误
define('PHP', 1 << 5); // 正确
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!