PHP Constants
PHP constants are name or identifier that can’t be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways:
- Using define() function
- Using const keyword
PHP constant: const keyword
PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a function. The constant defined using const keyword are case-sensitive.
<?php const MESSAGE="Hello const by JavaTpoint PHP"; echo MESSAGE; ?>
Constants vs Variables
- A constant, once defined can never be undefined but a variable can be easily undefined.
- There is no need to use dollar sign($) before constants during assignment but while declaring variables we use a dollar sign.
- A constant can only be defined using a define() function and not by any simple assignment.
- Constants dont need to follow any variable scoping rules and can be defined anywhere.
PHP also has a function called “get_defined_constants()” that returns an associative array of all the defined constants and their values.