Advertisement
Google Ad Slot: content-top
PHP Constants
Constants are similar to variables except that, once they are defined, their values cannot be changed during the execution of the script. Constants are useful for defining values that are used throughout a program but should remain the same.
Defining Constants
1. Using define() Function:
- The
define()function is used to create a constant. - Constants do not use the
$symbol when being defined or used. - They can store scalar values (strings, integers, floats, booleans) or arrays (from PHP 7).
Syntax:
define(name, value)
- name: Specifies the name of the constant
- value: Specifies the value of the constant
Note
Constant name is case-sensitive.
2. Using const Keyword (More common for defining class constants):
Constants can also be defined using the const keyword
Note
const vs. define()
constcannot be created inside another block scope, like inside a function or inside anifstatement.definecan be created inside another block scope.
PHP Constant Arrays
From PHP 7, you can create an Array constant using the define() function.
Constants are Global
Constants are automatically global and can be used across the entire script, including within functions and methods.
Note
Only defined constants are have Global scope.