PHP Constant Examples

Like in other programming languages, a constant in PHP is an identifier for a fixed value. Unlike variable, a constant is defined once and its value can’t be changed during an app’s lifecycle.

A valid constant name starts with a letter or underscore. It doesn’t start with a dollar sign ($) like variable.

Create a PHP Constant

We use define() function to create a constant.

define(name, value, case-insensitive)

//define a constant
define("WEB_ROOT", "https://www.tldevtech.com/");

//usage
echo "The root URL is ".WEB_ROOT;
function displayRoot(){
 echo WEB_ROOT;
}

Starting from PHP7, you can create an Array constant. The define() method is still used for array constant definition. The array then can be called like a normal one. The only difference is that its values are final.

define("phones", [
  "Samsung",
  "Apple"
]);
echo phones[0]; //Samsung

Create a PHP Class Constant

We can use constant in a class. However, it needs another approach to define and call a class’s constant.

class Phone
{
    const COUNTRY = 'Korea';

    function showOrigin() {
        echo  self::COUNTRY;
    }
}

$phone = new Phone();
$class->showOrigin();
echo $class::COUNTRY;

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close