PHP Constants

Constants in PHP are variables whose values cannot be changed once defined. They are useful for storing fixed values like database credentials, API keys, and configuration settings.

1. Defining Constants

PHP provides two ways to define constants:

  • define() function
  • const keyword

2. Using define()

The define() function is used to create a constant. It takes two arguments: the name of the constant (as a string) and its value.

<?php
    define("SITE_NAME", "MyWebsite");
    define("MAX_USERS", 100);

    echo "Welcome to " . SITE_NAME;
    echo "The maximum number of users is " . MAX_USERS;
    ?>

Try It Now

3. Using const

The const keyword is another way to define constants, but it can only be used inside the global scope or inside classes.

<?php
    const PI = 3.1416;
    echo "The value of PI is " . PI;
?>

Try It Now

4. Constants are Global

Constants are globally accessible throughout the script, even inside functions.

<?php
    define("GREETING", "Hello, World!");

    function sayHello() {
        echo GREETING;
    }

        sayHello();
?>

Try It Now

5. Case-Sensitivity

Constants defined with define() are case-sensitive by default, whereas const constants are always case-sensitive.

6. Magic Constants

PHP also provides predefined constants called “magic constants” that change depending on where they are used.

Magic Constant Description
__LINE__ Returns the current line number of the file
__FILE__ Returns the full path of the file
__DIR__ Returns the directory of the file
__FUNCTION__ Returns the function name
__CLASS__ Returns the class name

7. Example of Magic Constants

<?php
    echo "This line is: " . __LINE__;
    echo "This file is: " . __FILE__;
?>

Try It Now

Conclusion

Constants are essential for storing fixed values that should not change during script execution. Understanding the difference between define() and const, as well as PHP’s magic constants, will help you write better PHP scripts.