PHP Constants
PHP Constants
Constants in PHP are identifiers or names that are assigned fixed values, which cannot be changed during the program’s execution. Once a constant is defined, it cannot be undefined or redefined.
By convention, constant identifiers are written in uppercase letters. By default, constants are case-sensitive. A constant name must not start with a number; it should begin with a letter or an underscore, followed by letters, numbers, or underscores. Special characters (other than underscores) should be avoided.
Creating a Constant using define()
Function
The define()
function in PHP is used to create a constant. Here’s the syntax:
Syntax:
define( 'CONSTANT_NAME', value, case_insensitive )
Parameters:
name
: The name of the constant.value
: The value assigned to the constant.case_insensitive
: Defines whether the constant should be case-insensitive. The default isfalse
(case-sensitive).
Example: Creating constants using define()
function
<?php
// Creating a case-sensitive constant
define("SITE_TITLE", "LearnPHP");
echo SITE_TITLE . "\n";
// Creating a case-insensitive constant
define("GREETING", "Hello, World!", true);
echo greeting;
?>
Output:
LearnPHP
Hello, World!
Creating a Constant using const
Keyword
The const
keyword is another way to define constants, mainly used inside classes and functions. Unlike define()
, constants created using const
cannot be case-insensitive.
Syntax:
const CONSTANT_NAME = value;
Example:
<?php
const MAX_USERS = 100;
echo MAX_USERS;
?>
Output:
100
Constants are Global
Constants in PHP are global by default, meaning they can be accessed anywhere within the script, both inside and outside of functions or classes.
Example: Global access to constants
<?php
define("APP_VERSION", "1.0.5");
function displayVersion() {
echo APP_VERSION;
}
echo APP_VERSION . "\n";
displayVersion();
?>
Output:
1.0.5
1.0.5
Difference Between Constants and Variables
Though both constants and variables store values, they differ in several aspects:
Feature | Constants | Variables |
---|---|---|
Syntax | No dollar sign ($ ) | Starts with a dollar sign ($ ) |
Value | Immutable (cannot change) | Mutable (can be changed) |
Case Sensitivity | Case-sensitive (by default) | Case-sensitive |
Scope | Always global | Scope can vary (local or global) |
Declaration Method | define() or const | Use of $ symbol |
PHP Constant Class
Class Constants in PHP
The const
keyword is used to define a constant inside a class. Once a constant is declared, it cannot be changed. Class constants are always case-sensitive, though it’s a best practice to write them in uppercase letters. Unlike regular variables, class constants do not use a dollar sign ($
). By default, class constants are public and can be accessed from both inside and outside the class. They are useful when certain values within a class should remain constant throughout the program.
Accessing Class Constants
You can access class constants in two ways:
1. Outside the Class: You can access a class constant using the class name, followed by the scope resolution operator (::
), and then the constant name.
Example:
<?php
class Website {
// Declare class constant
const MESSAGE = "Welcome to LearnPHP";
}
// Access class constant outside the class
echo Website::MESSAGE;
?>
Output:
Welcome to LearnPHP
2. Inside the Class: Class constants can also be accessed within the class using the self
keyword followed by the scope resolution operator (::
) and the constant name.
Single-line comment example!
Output:
Welcome to LearnPHP
PHP Defining Constants
In production-level code, it is crucial to store information in either variables or constants rather than hard-coding values directly. A PHP constant is essentially an identifier for a value that remains constant over time (for example, the domain name of a website like www.example.com
). It’s a best practice to store all constants in a single PHP script for easier maintenance. A valid constant name must begin with a letter or underscore and does not require the $
symbol. Constants in PHP are global, meaning they can be accessed anywhere in the script regardless of scope.
To create a constant in PHP, we use the define()
function.
Syntax:
bool define(identifier, value, case-insensitivity)
Parameters:
- identifier: The name of the constant.
- value: The value assigned to the constant.
- case-insensitivity (Optional): Specifies whether the constant should be case-insensitive. By default, it is
false
, meaning the constant is case-sensitive.
Return Type:
The function returns TRUE
on success and FALSE
on failure.
Note: Starting from PHP 8.0, constants defined with define()
can be case-insensitive.
Example 1: Defining a case-insensitive constant
<?php
// Defining a case-insensitive constant
define("GREETING", "Hello, PHP World!", true);
echo greeting; // Case-insensitive access
echo GREETING;
?>
Output:
Hello, PHP World!
Hello, PHP World!
Example 2: Defining a case-sensitive constant
<?php
// Defining a case-sensitive constant
define("GREETING", "Hello, PHP World!");
echo greeting; // Will not work, case-sensitive
echo GREETING; // Correct usage
?>
Output:
greeting
Hello, PHP World!
Magic Constants in PHP
Magic constants in PHP are predefined constants that behave differently based on where they are used. Unlike regular constants, which are resolved at runtime, magic constants are resolved during compile-time. There are eight magic constants that begin and end with double underscores (__
). These constants are generally used for debugging or providing metadata about the file, function, or class.
Below are the magic constants with examples:
1. __LINE__: This magic constant returns the current line number of the file where it is used.
Syntax:
Example:
<?php
echo "The current line number is: " . __LINE__;
?>
Output:
The current line number is: 3
2. __FILE__:
This constant returns the full path and filename of the file in which it is used.
Syntax:
__FILE__
Example:
<?php
echo "The file name and path is: " . __FILE__;
?>
Output:
The file name and path is: /var/www/html/script.php
3. __DIR__:
This constant returns the directory of the file in which it is used.
Syntax:
__DIR__
Example:
<?php
echo "The directory is: " . __DIR__;
?>
Output:
The directory is: /var/www/html
4. __FUNCTION__:
This constant returns the name of the function in which it is used.
Syntax:
__FUNCTION__
Example:
<?php
function myFunction() {
echo "The function name is: " . __FUNCTION__;
}
myFunction();
?>
Output:
The function name is: myFunction
5. __CLASS__:
This constant returns the name of the class where it is used.
Syntax:
__CLASS__
Example:
<?php
class MyClass {
public function getClassName() {
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName();
?>
Output:
MyClass
Output:
Welcome to PHP!
15 + 25 = 40
6. __METHOD__:
This constant returns the method name where it is used.
Syntax:
__METHOD__
Example:
<?php
class ExampleClass {
public function exampleMethod() {
return __METHOD__;
}
}
$obj = new ExampleClass();
echo $obj->exampleMethod();
?>
Output:
ExampleClass::exampleMethod
7. __NAMESPACE__:
This constant returns the current namespace where it is used.
Syntax:
__NAMESPACE__
Example:
<?php
namespace MyNamespace;
class ExampleClass {
public function getNamespace() {
return __NAMESPACE__;
}
}
$obj = new ExampleClass();
echo $obj->getNamespace();
?>
Output:
MyNamespace
8. __trait__
: This magic constant returns the trait name where it is used.
Syntax:
__trait__
Example:
<?php
trait ExampleTrait {
function displayTrait() {
echo __trait__;
}
}
class ExampleClass {
use ExampleTrait;
}
$obj = new ExampleClass;
$obj->displayTrait();
?>
Output:
ExampleTrait
9. ClassName::class
: This magic constant returns the fully qualified class name.
Syntax:
ClassName::class
Example:
<?php
namespace Software_Portal;
class ExampleClass { }
echo ExampleClass::class; // ClassName::class
?>
Output:
Software_Portal\ExampleClass