Welcome to my series on every PHP keyword and its usage. Today’s item:
This keyword allows you to define a constant (an immutable value, can only be defined once) globally or for a specific class.
Values that can be placed into an expression are limited to:
- Any scalar literal, e.g.
- Any existing constant.
- An array literal containing any of the above, e.g.
[1, 2, 3].
- An expression made up of any of the above, e.g.
7 + 4or
"hello" . " world".
- Variables and function calls cannot be assigned to a constant.
- A global const statement cannot be used from within any control block (
forloop, etc.) or function.
- A class level const statement can only be used in the root of the class, and not from within method.
As an alternative, one can define a global constant using the
define() method, which accepts variables and function calls, as long as they return a scalar value, a resource or an array containing either.
define() method can be used from anywhere, including control blocks, functions and methods. This is likely to introduce needless complexity into your code, so it’s best to use
const when possible.
Author Callum Muir