search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the difference between const and define in PHP

Detailed explanation of the difference between const and define in PHP

##Available when defining constants in PHP What is the difference between const and define?

1. Const is used to define class member variables. Once defined, its value cannot be changed. define defines global constants that can be accessed anywhere.

2. define cannot be defined in a class, but const must be defined in a class, and variables defined by const must be accessed through class name::variable name.

3. Const constants cannot be defined in conditional statements.

4. const uses an ordinary constant name (static scalar), and define can use any expression as the name.

5. const is always case-sensitive, but define() can define case-insensitive constants through the third parameter.

6. Using const is simple and easy to read. It is a language structure in itself, and define is a method. Using const to define is much faster than define at compile time.

If you define a constant in a class, you cannot use define, but use const, as in the following example:


Recommended: "

PHP Tutorial"

<?php
//在类外面通常这样定义常量
define("PHP","111cn.net");
class MyClass
{
    //常量的值将始终保持不变。在定义和使用常量的时候不需要使用$符号
    const constant = &#39;constant value&#39;;

    function showConstant() {
        echo  self::constant . "<br>";
    }
}

echo MyClass::constant . "<br>";

$classname = "MyClass";
echo $classname::constant . "<br>"; // PHP 5.3.0之后

$class = new MyClass();
$class->showConstant();
echo $class::constant."<br>"; // PHP 5.3.0之后
//print_r(get_defined_constants());  //可以用get_defined_constants()获取所有定义的常量
?>

Generally define defines constants outside the class, const defines constants within the class, and const must be accessed through class name::variable name. However, php5.3 and above support defining constants outside of classes through const. See the following. This is OK:

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

I won’t go into the basic knowledge about constants here. In addition to the above, define and const are other things. Difference (from the Internet):

1.const cannot define constants in conditional statements, but define is possible, as follows:

<?php
if(1){
   const a = &#39;java&#39;;
 }    
echo a;  //必错
?>

2.const uses an ordinary constant name , define can take an expression as the name

<?phpconst  FOO = &#39;PHP&#39;; 
for ($i = 0; $i < 32; ++$i) { 
    define(&#39;PHP_&#39; . $i, 1 << $i); 
} 
?>

3.const can only accept static scalars, while define can take any expression.

<?php
const PHP = 1 << 5; // 错误
define(&#39;PHP&#39;, 1 << 5); // 正确 
?>

4.const itself is a language structure. And define is a function. So using const is much faster.

The two have something in common: both cannot be reassigned.

The following content is excerpted from Rotted_Pencil's blog post: The difference between defining constants in PHP, define() vs. const

Preface

Read it again on Stackoverflow today I came across a very interesting article, so I translated it and picked it up. The article was written by NikiC, one of the PHP development members, and its authority is unquestionable

Text

In PHP5.3, there are two ways to define constants:

1. Use the const keyword

2. Use the define() method

const FOO = ‘BAR’; 
define(‘FOO’,’BAR’);

The fundamental difference between the two methods is that const will define a constant when the code is compiled, while define will A constant is defined when the code is running. This causes const to have the following disadvantages:

const cannot be used in conditional statements. If you want to define a global variable, const must be at the outermost level of the entire code:

if (...) {    
    const FOO = &#39;BAR&#39;;    // 无效的
}
// but
if (...) {
   define(&#39;FOO&#39;, &#39;BAR&#39;); // 有效的
}

You may ask why I want to do this? One of the most common examples is when you are checking whether a constant has been defined:

if (!defined(&#39;FOO&#39;)) {
    define(&#39;FOO&#39;, &#39;BAR&#39;);
}

const can only be used to declare variables (such as numbers, strings, or true, false, null, FILE), and define() can also accept expressions. However, after PHP5.6 const can also accept constant expressions:


const BIT_5 = 1 << 5;    // 在PHP5.6之后有效,之前无效
define(&#39;BIT_5&#39;, 1 << 5); // 一直有效

const constant names can only use straightforward text, while define() allows you to use any expression to name them. Constant naming. This allows us to do the following:

for ($i = 0; $i < 32; ++$i) {
    define(&#39;BIT_&#39; . $i, 1 << $i);
}

const-defined constants are case-sensitive, but define allows you to turn off its case-sensitivity by setting its third parameter to true:

define(&#39;FOO&#39;, &#39;BAR&#39;, true);
echo FOO; // BAR
echo foo; // BAR

The above are the points you need to pay attention to. So now I will explain the following, why I personally always use const without involving the above situations:

const is more readable and beautiful.

const defines constants under the current namespace by default, and using define requires you to specify the full path of the entire namespace:

namespace A\B\C; 
// 如果要定义常量 A\B\C\FOO: 
const FOO = ‘BAR’; 
define(‘A\B\C\FOO’, ‘BAR’);

Since PHP5.6, const arrays can also be defined. is a constant. Define currently does not support this function, but this function will be implemented in PHP7:

const FOO = [1, 2, 3];    // 在PHP 5.6中有效 
define(‘FOO’, [1, 2, 3]); // 在PHP 5.6无效, 在PHP 7.0有效

Because const is executed during compilation, it is faster than define.

Especially when using define to define a large number of constants, PHP will run very slowly. People even invented things like apc_load_constantshide to avoid this problem

Compared with define, const can double the efficiency of defining constants (on a development machine configured with XDebug, this difference will be even greater). But in terms of query time, there is no difference between the two (because both use the same query table)

The last thing to note is that const can be used in class and interface, while define is Those who cannot do this:

class Foo {
    const BAR = 2; // 有效
}
class Baz {
    define(&#39;QUX&#39;, 2); // 无效
}

Summary

Unless you need to use expressions or define constants in conditional statements, otherwise you'd better use const just for the simple readability of the code!

For more PHP related knowledge, please visit PHP Chinese website!

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

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.