PHP Constant

Last updated on

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!

Frequently Asked Questions (FAQs)

  • What is the difference between `define()` and `const` in PHP?

    The primary difference is where and how you can use them:
    - define() is used to define constants at runtime. It allows for dynamic naming and can define constants outside of classes or functions.
    define('SITE_NAME', 'MyWebsite');
    - const is a language construct, which means it is used to define constants at compile-time. It’s also more commonly used within classes.
    const PI = 3.14159;
  • Can you change the value of a constant in PHP?

    No, once a constant is defined using either define() or const, its value cannot be changed. If you attempt to change it, PHP will throw an error. For example:
    define('MAX_LIMIT', 100);
    MAX_LIMIT = 200; // Error!
  • How do you check if a constant is defined in PHP?

    You can use the defined() function to check if a constant is already defined. It returns true if the constant exists, and false otherwise.
    if (defined('MAX_LIMIT')) {
      echo MAX_LIMIT;
    }else {
    echo "Constant not defined.";
    }
  • What are the data types supported by PHP constants?

    Constants in PHP can hold the following data types:
    - int
    - float
    - string
    - boolean
    For example:
    define('PI', 3.14159);
    define('SITE_NAME', 'MyWebsite');
    define('IS_ACTIVE', true);
  • What are magic constants in PHP?

    Magic constants are predefined constants that change depending on where they are used. Some of the most common magic constants include:
    - __FILE__: Returns the full path and filename of the file.
    - __LINE__: Returns the current line number in the file.
    - __DIR__: Returns the directory of the file.
    For example:
    echo __FILE__; // Outputs the full path to the script
  • How do you define array constants in PHP?

    Since PHP 7.0, you can define array constants using the define() function. This is helpful when you want a constant that holds multiple values.
    define('USER_ROLES', ['Admin', 'Editor', 'Subscriber']);
    echo USER_ROLES[0]; // Outputs: Admin
  • What are class constants in PHP?

    Class constants are constants that are defined within a class using the const keyword. These constants can be accessed via the class name, followed by the scope resolution operator ::.
    class Math {
       const PI = 3.14159;
    }
    
    echo Math::PI; // Outputs: 3.14159
  • What is the visibility of constants in PHP classes?

    Since PHP 7.1, you can define the visibility of class constants as public, protected, or private. By default, class constants are public.
    class Access {
       public const PUBLIC_CONST = 'Public';
       protected const PROTECTED_CONST = 'Protected';
       private const PRIVATE_CONST = 'Private';
    }
    
    echo Access::PUBLIC_CONST; // Outputs: Public
  • Can constants be case-insensitive in PHP?

    Yes, constants can be case-insensitive if you define them with define() and pass true as the third parameter. However, this feature is deprecated in PHP 7.3 and removed in PHP 8.0.
    define('GREETING', 'Hello', true); 
     echo GREETING; // Outputs: Hello 
     echo greeting; // Outputs: Hello (before PHP 8.0)
  • Can you define constants in namespaces?

    Yes, you can define constants in namespaces just like other elements such as functions or classes.
    namespace MyNamespace {
       const GREETING = 'Hello, World!';
    }
    
    namespace {
       echo \MyNamespace\GREETING; // Outputs: Hello, World!
    }
Share on: