A constant is the identifier (name) of a simple value ). As its name implies, this value cannot be changed during script execution (except for so-called magic constants, they are actually not constants ). Constants are case sensitive by default. By convention, constant identifiers are always capitalized.
Constant names and any other PHP labels follow the same naming rules. A valid constant name starts with a letter or underline followed by any letter, number, or underline. The regular expression is like this: [A-Za-Z _ \ x7f-\ xFF] [a-zA-Z0-9 _ \ x7f-\ xFF] *
Valid and invalid constant names
<? PHP
// Valid constant name
Define ("w3sky", "something ");
Define ("w3sky2", "something else ");
Define ("w3sky_bar", "something more ")
// The constant name is invalid.
Define ("2w3sky", "something ");
// This is valid, but shoshould be avoided:
// PHP may one day provide a magical constant
// That will break your script
Define ("_ w3sky _", "something ");
?>
Note: here the letter is a-Z, A-Z, and ASCII characters from 127 to 255 (0x7f-0xff.
Like superglobals, the constant range is global. You can access constants anywhere in the script without specifying the scope. For more information, see the variable range in the manual.
Syntax
You can use the define () function to define constants. Once a constant is defined, it cannot be changed or undefined.
Constants can only contain scalar data (Boolean, integer, float, and string ).
You can simply get the value of a constant by specifying its name. Do not add the $ symbol before the constant. If the constant name is dynamic, you can also use the Function
To read the value of a constant. Use get_defined_constants () to obtain 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 it wants the name of the constant, just like calling it with a string (constant corresponds to "constant "). At this time, an e_notice-level error will be issued. See why $ w3sky [bar] is incorrect in the Manual (unless bar is defined as a constant with define ). If you only want to check whether a constant is defined, use the defined () function.
Constants and variables are different:
* There is no dollar sign before a constant ($ );
* Constants can only be defined using the define () function, but cannot be defined using the value assignment statement;
* Constants can be defined and accessed anywhere regardless of the variable range rules;
* Once defined, a constant cannot be redefined or canceled;
* The constant value can only be a scalar.
Define Constants
<? PHP
Define ("constant", "Hello world .");
Echo constant; // outputs "Hello world ."
Echo constant; // outputs "constant" and issues a notice.
?>