Home > Backend Development > PHP Tutorial > Analyze the application differences between const and define in php_PHP tutorial

Analyze the application differences between const and define in php_PHP tutorial

WBOY
Release: 2016-07-21 15:06:04
Original
871 people have browsed it

1. Const is used to define class member variables. Once defined, its value cannot be changed. define defines global constants that can be accessed anywhere.
2. define cannot be defined in a class but const can.
3. Const cannot define constants in conditional statements

Copy code The code is as follows:

if (... ) {
const FOO = 'BAR'; // invalid
}
but
if (...) {
define('FOO', 'BAR'); // valid
}

4. const uses an ordinary constant name, and define can use an expression as the name.
Copy code The code is as follows:

const FOO = 'BAR';
for ($i = 0; $ i < 32; ++$i) {
define('BIT_' . $i, 1 << $i);
}

5. const can only Accepts static scalars, while define can take any expression.
Copy code The code is as follows:

const BIT_5 = 1 << 5; // invalid
but
define('BIT_5', 1 << 5); // valid

6. const is always case-sensitive, but define() can define the size through the third parameter Write insensitive constants
Copy code The code is as follows:

define('FOO', 'BAR', true);
echo FOO; // BAR
echo foo; // BAR

Summary:
Using const is simple and easy to read, It itself is a language structure, and define is a method. Using const to define is much faster than define at compile time.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327648.htmlTechArticle1. const is used to define class member variables. Once defined, its value cannot be changed. define defines global constants that can be accessed anywhere. 2. define cannot be defined in a class but const can. ...
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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template