Skip to main content

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", "");
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.