PHP Constant
Last updated onIn 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
, or with the keyword define()
.const
1- The "define()" Function
Probably the most common way of setting constants would be by the use of the
function, which takes two parameters: the name of the constant (must be a string) and its value.define()
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs: MyWebsite
Here,
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.SITE_NAME
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
keyword. Unlike const
, which is global, define()
may also be used inside classes. That makes it useful for the purpose of class-specific constant definitions.const
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
inside a class than to hold values that are shared by all instances of your class. For instance, const
would be a good candidate for a constant inside a class called PI
since it never changes.Math
class Geometry {
const SHAPE_CIRCLE = "Circle";
const SHAPE_SQUARE = "Square";
}
echo Geometry::SHAPE_CIRCLE; // Outputs: Circle
Above, in the
class, we have declared two constants: Geometry
, SHAPE_CIRCLE
. We can access these constants using the scope resolution operator SHAPE_SQUARE
.::
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
, or protected
. It is public by default; setting the visibility explicitly enhances encapsulation and controls how class constants are accessed.private
class Access {
public const PUBLIC_CONST = "Public";
protected const PROTECTED_CONST = "Protected";
private const PRIVATE_CONST = "Private";
}
echo Access::PUBLIC_CONST; // Outputs: Public
or Access::PROTECTED_CONST
would result in an error due to visibility.Access::PRIVATE_CONST
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
function; it checks if a constant exists:defined()
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
, and PHP_OS
.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
constant makes it very easy to determine whether a particular feature or function becomes available.PHP_VERSION
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:
: The full pathname and filename of the file.__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
, you get the full path to the file where it is used:__FILE__
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
function outside any function or class, allowing it to be accessed in any scope throughout your whole application.define()
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
. 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()
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
function, the define()
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.const
Thank you for reading. Happy Coding!
Frequently Asked Questions (FAQs)
What is the difference between `define()` and `const` in PHP?
Can you change the value of a constant in PHP?
How do you check if a constant is defined in PHP?
What are the data types supported by PHP constants?
What are magic constants in PHP?
How do you define array constants in PHP?
What are class constants in PHP?
What is the visibility of constants in PHP classes?
Can constants be case-insensitive in PHP?
Can you define constants in namespaces?