Home  >  Article  >  Backend Development  >  How to declare constants in php?

How to declare constants in php?

怪我咯
怪我咯Original
2017-06-20 10:11:171950browse

Constants can be understood as quantities whose values ​​do not change. Once a constant is defined, it cannot be changed anywhere else in the program script.

You can use the define() function to define constants. After PHP 5.3.0, you can use the const keyword to define constants outside the class definition. Once a constant is defined, it cannot be changed or undefined.

Constants can only contain scalar data ( boolean , integer , float and string ). You can define resource constants, but they should be avoided as they can cause unpredictable results.

You can get the value of a constant simply by specifying its name. Unlike variables, you should not add the $ sign in front of a constant. If the constant name is dynamic, you can also use the function constant() to get the value of the constant. Use get_defined_constants() to get a list of all defined constants.

Note: Constants and (global) variables are in different namespaces. This means that for example TRUE and $TRUE are different.

If an undefined constant is used, PHP assumes that what is wanted is the name of the constant itself, as if calling it with a string (CONSTANT corresponds to "CONSTANT"). An E_NOTICE level error will be issued. See the manual for why $foo[bar] is wrong (unless bar is previously defined as a constant using define() ). If you just want to check whether a certain constant is defined, use the defined() function.

Example #1 Define constants

<?php
define ( "CONSTANT" ,  "Hello world." );
echo  CONSTANT ;  // outputs "Hello world."
echo  Constant ;  // 输出 "Constant" 并发出一个提示级别错误信息
?>

Example #2 Use the keyword const to define constants

<?php
// 以下代码在 PHP 5.3.0 后可以正常工作
const  CONSTANT  =  &#39;Hello World&#39; ;

echo  CONSTANT ;
?>

Note:

And use define() to define constants In contrast, constants defined using the const keyword must be in the topmost scope because they are defined at compile time. This means that you cannot use const to define constants inside functions, loops, and if statements.

The above is the detailed content of How to declare constants 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