Define and Use Constants in PHP

PHP has a lot of constants that are available for use in your code. Some of these constants are predefined by PHP, and others are defined by extensions or even your own code.

To define a constant, you can use the define() function. Once a constant is defined, it can never be changed or undefined. A constant name must start with a letter or an underscore. It can only contain alphanumeric characters and underscores.

define("GREETING", "Hello world!");
echo GREETING; //"Hello world!"

define("WEB_ROOT", "https://tleapps.com/");
echo "The URL is ".WEB_ROOT;

function displayRoot(){
 echo WEB_ROOT;
}
//define constant in a class
class Language
{
    const COUNTRY = 'Japan';
    const CODE = 'jp';

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

$language = new Language();
$class->showOrigin(); //'Japan'
echo $class::CODE; 'jp'

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