Constants are Global

Yes, constants in PHP are global by default. This means that once a constant is defined, it can be accessed from anywhere in the PHP script, regardless of the scope.

For example, if you define a constant at the top of a PHP script, you can use it in any function or class within that script without having to pass it as a parameter or declare it again.

Here’s an example of how to define and use a constant in PHP:

define('PI', 3.14159);

function calculateArea($radius) {
    return PI * $radius * $radius;

echo calculateArea(2); // Output: 12.56636

In this example, the constant PI is defined at the top of the script and is then used inside the calculateArea() function to calculate the area of a circle. Even though the PI constant is defined outside of the function, it can still be accessed and used inside the function.

It’s important to note that constant values cannot be changed once they are defined, so any modifications to the constant must be done by redefining it using the define() function. Additionally, constants are case-sensitive by default, so it’s important to use the same case when accessing the constant throughout the script.

Scroll to Top