Home >Backend Development >PHP Tutorial >What is the difference between define and const in php? (detailed explanation)

What is the difference between define and const in php? (detailed explanation)

不言
不言forward
2019-01-07 11:13:383980browse

The content of this article is about what is the difference between define and const in php? (Detailed explanation) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There are two ways to define constants in PHP: define and const. What is the difference between the two?

const CONSTANCE = 'const';
define('CONSTANCE',  'const');

The const keyword can define constants outside the class definition from PHP 5.3 onwards

const can be defined inside the class, but define cannot.
The constants defined by const are in the current namespace, and define must write the specific namespace to define the namespace for execution.

class Foo {
    const BAR = 2;
}


class Foo2 {
    define("BAR", 3); //无效的
}

//命名空间的示例
namespace A{
    const A1 = 1; //处在命名空间A中
    define('A2',  2); //全局可调用
    define('A\A3', 3); //处在命名空间A中
}

namespace B{
    use const \A\A1;
    use const \A\A3;
    
    echo A1;
    echo A2; //全局调用
    echo A3;
}

const defines constants in the compilation stage, define defines constants in the preprocessing stage

const defines constants in the compilation stage, and must be in the final state when defining constants. Top area of ​​action.
So it cannot be defined in conditional statements such as if.

define defines constants, also called macro definitions. Macros can be described as replacing certain text patterns according to a series of predefined rules.
define can exist in a branch.

Theoretically, using const will be a little faster than defining.

const only accepts scalar data, (such as integer, string, boolean and float, etc.); define can accept any expression

define('BIT_5',   1<<5); 
const BIT_5 =     1<<5; //5.6之后才有效
Starting from PHP 5.6, const can also accept arrays and expressions
define can accept resource type, const cannot

const constant name can only be simple characters, define can be any expression

const STR = 'string';
$i = 1;
define("STR_" . $i,  STR);

const is case sensitive, define can control case sensitivity through the third parameter.

A few other questions

Can the constant arrays defined by const and define change the elements in them?

Can you use defined to check constants defined by const?

The above is the detailed content of What is the difference between define and const in php? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete