PHP Constant
In PHP, a constant is a value that cannot be changed during the execution of the script. Once defined, a constant's value remains the same throughout the script. Constants are usually defined using the define()
function or, in PHP 7.0 and later, using the const
keyword.
Defining Constants
Using define()
define("PI", 3.14159);
echo PI; // Output: 3.14159
In this example, PI
is defined as a constant with a value of 3.14159
. Once defined, PI
cannot be changed.
Using const
const GRAVITY = 9.81;
echo GRAVITY; // Output: 9.81
Here, GRAVITY
is defined as a constant with a value of 9.81
. Similar to define()
, once GRAVITY
is set, it cannot be altered.
Key Points about Constants
-
Case Sensitivity: By default, constants are case-sensitive when defined using
define()
. However, with theconst
keyword, constants are case-sensitive by default and cannot be changed.define("GREETING", "Hello World"); echo greeting; // Output: Notice: Undefined constant "greeting"
In contrast:
const GREETING = "Hello World"; echo GREETING; // Output: Hello World
-
Global Scope: Constants are globally accessible across the script, meaning you can access them from any part of your code without needing to pass them as parameters or use
global
keyword.define("USERNAME", "admin"); function printUsername() { echo USERNAME; // Output: admin } printUsername();
-
No
$
Sign: Unlike variables, constants are defined without the dollar sign ($
).define("MY_CONSTANT", "Some Value"); echo MY_CONSTANT; // Output: Some Value
-
Use in Classes: When using
const
within a class, constants are accessed using the class name and the scope resolution operator (::
).class MathConstants { const E = 2.71828; } echo MathConstants::E; // Output: 2.71828
Constants are useful for defining values that remain unchanged throughout the execution of your script, such as configuration values, mathematical constants, and other fixed data.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.