Home > Backend Development > PHP Tutorial > When defining constants in php, the difference between const and define

When defining constants in php, the difference between const and define

WBOY
Release: 2016-07-28 08:27:11
Original
857 people have browsed it

【Ask】When defining constants in PHP, what is the difference between const and define?

【Answer】Using const makes the code simple and easy to read. Const itself is a language structure, while define is a function. In addition, const is much faster than define during compilation.

(1).const is used for the definition of class member variables. Once defined, it cannot be modified. define cannot be used for the definition of class member variables, but can be used for global constants.

(2).const can be used in classes, define cannot.

(3).const cannot define constants in conditional statements.

For example:

if (...){

const FOO = 'BAR'; // invalid invalid

}

if (...) {

define('FOO', 'BAR' ); // Valid valid

}

(4).const uses an ordinary constant name, define can use an expression as the name.

const FOO = 'BAR';

for ($i = 0; $i < 32; ++$i) {

define('BIT_' . $i, 1 << $i);

}

(5).const can only accept static scalars, while define can take any expression.

For example:

const BIT_5 = 1 << 5; // Invalid invalid

define('BIT_5', 1 << 5); // Valid valid

(6).const definition The constants are case-sensitive, and define can specify whether it is case-sensitive through the third parameter (true means case-insensitive).

For example:

define('FOO', 'BAR', true);

echo FOO; // BAR

echo foo; // BAR

The above has introduced the difference between const and define when defining constants in PHP, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template