PHP constants definition and usage

We usually do not often change values ​​are defined as constants, constants generally used to represent all uppercase, without a dollar sign in front, but also reduce errors team development. Const and then define what difference does it?


1, const is a language construct; and define a function, case sensitivity can be specified by the third parameter. true if case-insensitive defaults to false

define('PI', 3.14, true);

2, const easier to read than to define much faster compile time.

3, const may be used in a class, a constant defines the class members, can not be defined and modified; DEFINE not be used in class, it can be used for global variables

Copy the code
class MyClass
{
    const CONS = 'constant value' ;

    function showConstant() { echo self::CONS . PHP_EOL; echo constant('CONS'); } }
Copy the code

4, const is defined at compile time, it must be in the role of regional top-most, can not be used in functions, loops and if conditions; and define a function, which is able to call a function where you can use

IF (... ) {
 const = FOO 'the BAR';     // Invalid invalid } IF (... ) { DEFINE ( 'FOO', 'the BAR'); // valid valid}

5, const only with ordinary constant name, define constant names can have expressions

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

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

const BIT_5 = 1 << 5;    // valid since PHP 5.6
define('BIT_5', 1 << 5); // 有效的valid

Guess you like

Origin www.cnblogs.com/xiaozhang666/p/11027613.html