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

Source: Internet
Author: User
"Q" When defining constants in PHP, what is the difference between const and define?

The "answer" uses the const to make the code easy to read, and the const itself is a language structure, and define is a function. In addition, const is much faster to compile than define.

(1). Const is used to define a class member variable, which is not modifiable once defined. Define is not available for definition of class member variables and can be used for global constants.

(2). Const can be used in a class, define cannot.

(3). Const cannot define a constant in a conditional statement.

For example:

if (...) {

Const FOO = ' BAR '; Invalid invalid

}

if (...) {

Define (' FOO ', ' BAR '); The effective valid

}

(4). Const takes an ordinary constant name, and define can use an expression as its name.

Const FOO = ' BAR ';

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

Define (' Bit_ '. $i, 1 << $i);

}

(5). Const can only accept static scalars, and define may take any expression.

For example:

Const BIT_5 = 1 << 5; Invalid invalid

Define (' Bit_5 ', 1 << 5); The effective valid

(6). const-defined constants are case-sensitive, and define can specify case sensitivity by using the third argument (true for case insensitivity).

For example:

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

Echo FOO; BAR

echo foo; BAR

The above describes the definition of constants in PHP, the difference between the const and define, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.