Constants define and const are defined in PHP

Source: Internet
Author: User
Tags constant definition

We usually define non-constant values as constants, which are generally represented in all capitals, with no dollar sign in front of them, and can reduce errors in team development. So what's the difference between a define and a const?


1, const is a language structure, and define is a function that can be specified by the third argument for case sensitivity. True to indicate case insensitive, default to False

Define true);

2. Const is easy to read and compiles much faster than define.

3, the const can be used in the class, for the class member constant definition, after definition cannot be modified; Define cannot be used in a class, can be used for global variables

class myclass{    const CONS = ' constant value ';     function showconstant () {        echo  php_eol;         Echo  constant (' CONS ');}          }

4, const is defined at compile time, so must be at the top of the scope, not in the function, loop and if conditions, and define is a function, that is, can call the function of the place can be used

if (... {const FOO = ' BAR ';    // Invalid Invalid }if (... ) {define//  valid valid}

5, const can only use the ordinary constant name, define constant name can have an expression

Const  FOO = ' BAR ';  for ($i$i <, + +$i) {define$i$i);}

6, const defined constants can only be static constants, define can be any expression

Const Bit_5 = 1 << 5;    // valid since PHP 5.6 Define // the effective valid

Define constants define and const in PHP

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.