Difference between phpconst and define (how to define constants in php classes)

Source: Internet
Author: User
As we all know, define defines constants. what if we define constants in a class? Of course, define cannot be used, but const can be used, for example: & amp; lt ;? Php // The constant define (& quot; PHP & quot;, & quot; phpdd is usually defined out of the class.

As we all know, define defines constants. what if we define constants in a class? Of course, define cannot be used, but const can be used, for example:


 ";}} Echo MyClass: constant ."
"; $ Classname =" MyClass "; echo $ classname: constant ."
"; // $ Class = new MyClass (); $ class-> showConstant (); echo $ class: constant ."
"; // PHP 5.3.0 and later // print_r (get_defined_constants (); // you can use get_defined_constants () to get all defined constants?>

Generally, define defines constants outside the class, const defines constants within the class, and const must be accessed by class name: variable name. However, php5.3 and above support defining constants through const outside the class, as shown below, it is OK:


     const a = "abcdef";    echo a;?>

I will not talk about the basic knowledge of constants here. apart from the above, other differences between define and const (from the network ):

1. const cannot define constants in condition statements, but define is acceptable, as follows:


 

2. const uses a normal constant name, and define can use an expression as the name


 

3. const can only accept static scalar, while define can use any expression.


 

4. const itself is a language structure. Define is a function. Therefore, using const is much faster.

There are so many differences between const and define 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.