Table of Content
In regard to the use of constants in PHP, clear understanding of their definition and use could be critical in basing your coding on efficiency and reliability. Constants are a great way through which you can outline values that do not change during the execution of your script, saving you from repetitive hardcoding.
Whether you are setting up a configuration value that remains constant throughout your application or leveraging constants to simplify class structures, they have an integral place within your arsenal of PHP development.
Anyway, let’s take a look at what constants are.
What is a Constant in PHP?
In PHP, a constant is a variable whose value one can never change. Once you declare a constant, it becomes immutable, making it perfect for values you might not want to accidentally change later in your code. Constants are very often used for settings like database credentials, file paths, or any other data that should remain consistent throughout the script’s lifecycle.
Unlike variables, there is no need to use the dollar sign symbol ($) before the name of a constant. The value of a constant can be an integer, float, string, or boolean; however, once it is set, that value cannot be modified.
Defining Constants in PHP
There are primarily two ways to define a constant in PHP: either with the function define(), or with the keyword const.
1- The “define()” Function
Probably the most common way of setting constants would be by the use of the define() function, which takes two parameters: the name of the constant (must be a string) and its value.
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs: MyWebsite
Here, SITE_NAME is the constant, its value being a string “MyWebsite”. You can refer to SITE_NAME anywhere in your code now, without any possibility of its value changing.
You can also define constants with an array using define(), which became possible in PHP 7.0:
define("COLORS", ["Red", "Green", "Blue"]);
echo COLORS[0]; // Outputs: Red
This makes it more flexible when working with several constant values besides keeping your code tidy.
2- Const Keyword
Yet another definition of a constant may be given with the const keyword. Unlike define(), which is global, const may also be used inside classes. That makes it useful for the purpose of class-specific constant definitions.
const PI = 3.14159;
echo PI; // Outputs: 3.14159
The const keyword can also be used in classes, which comes in quite useful if you want to make use of constants that are bound to the class itself. Class constants are like static class properties but, by definition, cannot be changed once they are defined:
class Math {
const PI = 3.14159;
}
echo Math::PI; // Outputs: 3.14159
In object-oriented PHP, constants in classes are used to represent values that are not going to change, like thresholds, or settings that regard the class configuration.
Constants in Classes
In PHP classes, there is another use of the constants — since a constant cannot be changed, there is no other use for the keyword const inside a class than to hold values that are shared by all instances of your class. For instance, PI would be a good candidate for a constant inside a class called Math since it never changes.
class Geometry {
const SHAPE_CIRCLE = "Circle";
const SHAPE_SQUARE = "Square";
}
echo Geometry::SHAPE_CIRCLE; // Outputs: Circle
Above, in the Geometry class, we have declared two constants: SHAPE_CIRCLE, SHAPE_SQUARE. We can access these constants using the scope resolution operator ::.
Constant Visibility in Classes
Also, since PHP 7.1, it has been possible to define the visibility of constants in classes. That is, constants could be defined to be public, protected, or private. It is public by default; setting the visibility explicitly enhances encapsulation and controls how class constants are accessed.
class Access {
public const PUBLIC_CONST = "Public";
protected const PROTECTED_CONST = "Protected";
private const PRIVATE_CONST = "Private";
}
echo Access::PUBLIC_CONST; // Outputs: Public
Access::PROTECTED_CONST or Access::PRIVATE_CONST would result in an error due to visibility.
Can You Change the Value of a Constant?
The short answer: no, you cannot change the value of a constant in PHP after it’s defined. Unlike variables, constants can’t be changed once set, which actually is part of what makes them so useful. Trying to reassign the value of a constant will result in an error.
define("MAX_LIMIT", 100);
MAX_LIMIT = 200; // This would cause a compile-time error.
Constants have been developed to offer your code some stability in terms of values, since some of them are intended not to be changed at any point in the execution.
Checking Whether a Constant Is Already Defined
Sometimes you want to check if the constant is already defined and then attempt to use it. This is handy when your constants are set dynamically or conditionally. PHP has the defined() function; it checks if a constant exists:
if (defined('MAX_LIMIT')) {
echo MAX_LIMIT;
} else {
echo "Constant not defined.";
}
It returns true if the constant has already been defined and false otherwise.
PHP Predefined Constants
PHP already contains a number of predefined constants that return information about the PHP Environment and its configuration. A few commonly used predefined constants include PHP_VERSION, PHP_OS, and PHP_EOL.
echo PHP_VERSION; // Outputs the current PHP version
echo PHP_OS; // Outputs the operating system PHP is running on
echo PHP_EOL; // Outputs the correct end-of-line character for the operating system
These predefined constants can be useful in adapting your code to behave differently depending on either the PHP version or platform your script is running on. For example, using the PHP_VERSION constant makes it very easy to determine whether a particular feature or function becomes available.
Magic Constants
PHP also supports a number of “magic constants” that change, depending upon where they are used. In the strictest sense, these aren’t really constants at all but are context-sensitive and return information about the file or function they’re used in.
Some common magic constants include:
__FILE__: The full pathname and filename of the file.__LINE__: The number representing the current line in the file.__DIR__: Directory of the file.__FUNCTION__: The function name.__CLASS__: The class name.
For example, using __FILE__, you get the full path to the file where it is used:
echo __FILE__; // Outputs the full path and filename of the script
Magic constants are especially useful for debugging and logging purposes because with them you can get some context about the point of the script’s execution dynamically.
Defining Global Constants
If you need the same constant to be accessed from anywhere, you have to define a global constant. To do so, you declare the use of the define() function outside any function or class, allowing it to be accessed in any scope throughout your whole application.
define('SITE_URL', 'https://example.com');
echo SITE_URL; // Outputs: https://example.com
This constant can then be used anywhere within the script and prevents multiple hardcodings of the site URL.
Defining Array Constants
Since PHP 7.0, you can define array constants using define(). This allows you to provide a much more complex constant data structure, which could be very useful in the case of configurations or predefined sets of values.
define('USER_ROLES', ['Admin', 'Editor', 'Subscriber']);
echo USER_ROLES[0]; // Output: Admin
Array constants help you to structure your data in a more effective manner without relying on variables that might eventually change.
Wrapping Up
PHP constants are one of the most powerful ways to help maintain predictability and manageability of your code. Be it with the define() function, the const keyword, or predefined/magic constants, there are different ways you can manage to map a constant name to a value and retain that consistency and accessibility throughout your scripts. Mastering constants will enhance the structure, readability, and efficiency of your code while avoiding certain risks associated with key value modifications at runtime.
Thank you for reading. Happy Coding!
Similar Reads
The PHP is_readable helps you validate file readability before any operation like read or include files. What Is PHP is_readable? The is_readable() function…
PHP comparison operators allow you to compare values in many ways, and this simplifies the process of checking whether values…
When you deal with text in PHP, sometimes you need to break it into parts. This is common when users…
PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…
The array_intersect_ukey is used to compare arrays by keys with a custom function in PHP. It returns matches by keys…
You can use your Raspberry Pi as a personal web server or tool that runs in your home. You do…
If you find a word that does not fit and want to fix it. You can use the PHP str_replace…
Sometimes, when you run a script, you may encounter an error because the directory you're trying to access doesn't exist.…
One of the important tasks is retrieving documents from a collection. MongoDB help us to make this process, but understanding…
You use integers (int) in PHP to count items, set page numbers, handle IDs, and manage loop counters. In this…