SyntaxYou can define a constant by using the define-function or by using the const keyword outside a class definition as of PHP 5.3.0. While define allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined. When using the const keyword, only scalar data (boolean, integer, float and string) can be contained in constants prior to PHP 5.6. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results. You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants to get a list of all defined constants.
If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first define bar as a constant). This does not apply to (fully) qualified constants, which will raise a fatal error if undefined. If you simply want to check if a constant is set, use the defined function. These are the differences between constants and variables:
Example #1 Defining Constants
<?php
Example #2 Defining Constants using the const keyword
<?php
See also Class Constants. |