Constants in PHP represents those values which can’t be changed after initialization within a script.
Constants in PHP are case-sensitive, by default.
Constant names must start with an alphabet or underscore.
How to define constants in PHP ?
Constants can be defined using define() method. It has following definition –
define(name,value,case-insensitivity)
Parameters –
– name : The name of constant
– value : Value of constant
– case-insensitivity : if set to true, the constant will become case-insensitive. Default is false and it is optional parameter.
Example
Creating a constant with case-sensitive name-
In the above example, constant declared is case-sensitive, it means you cannot access this constant using ‘Welcome’ or ‘weclome’ or ‘weLcome’ etc. This will generate error that CONSTANT is not defined.
Declaring case-insensitive constants –
In this example, the constant ‘welcome’ is defined case-insensitive, that means we can access it using ‘Welcome’ or ‘welcome’ etc.
Constants Vs Variables
– There is no need to use $ sign in constants .
– Constants cannot be declared in simple expressions, define() function is used.
– Constants are global and can be accessed anywhere.
– Once the constant is defined, it’s value must not be changed.
Scopes of Constants
Unlike, declaring variables, constants are having global scopes. It means, a constant once declared, can be used anywhere within the script.