Home>Article>Backend Development> What is the difference between const and define in php

What is the difference between const and define in php

王林
王林 Original
2021-09-06 15:29:49 2872browse

The difference between const and define in php is: const is a language structure, define is a function; const can be used in classes, but define cannot; const cannot be used in conditional branches, but define can.

What is the difference between const and define in php

The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.

We know that there are two ways to define constants in PHP, namely const and define. So many beginners may have a question when using const and define. What is the difference between them?

Let’s take a look at the difference between the two:

const is a language structure, and define is a function.

const can be used in classes, but define cannot. Before PHP5.3, const could only be used within a class, but since PHP5.3 it can also be used outside the class.

const cannot be used in conditional branches, but define can.

const can only use ordinary constant names, define can use expressions.

const only accepted static scalars before PHP5.6. From PHP5.6 onwards, expressions can be used, and define can use expressions.

The constants defined by const are case-sensitive, and define can specify whether it is case-sensitive through the third parameter (true is not sensitive; false is sensitive, the default is false).

const considers the namespace when defining constants, but define does not. To put it simply, const can define constants with the same name in different namespaces, but define cannot.

Constants can be accessed directly through the constant name or through the constant() function. All defined constants can be obtained through get_defined_constants().

Recommended learning:php training

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn