happy cat image

Start Web Coding

Your First step toward web coding,
Start Web Coding

change UI

Constants in Class

I can declare constants that are used in that class.
To declare a constant, use the const keyword. Constants are declared in uppercase letters. Of course it's a promise.

How to declare a constant in a class

const constant name = value;

How constants are used in class

self::constant name;

So let's declare and use a constant

<?php
    class Car
    {
        const TRUNK = true;

        public function checkTrunk()
        {
            return self::TRUNK;
        }
    }

    $car = new Car;
    if($car->checkTrunk() == true){
        echo "This car has a trunk." ;
    } else {
        echo "This car has no trunk." ;
    }
?>

Result

To use a constant from a class outside the class, use instance ::.

How To Use constant in class

Instance :: constant name;
<?php
    class Car
    {
        const TRUNK = true;

        public function checkTrunk()
        {
            return self::TRUNK;
        }
    }

    $car = new Car;
    if($car::TRUNK == true){
        echo "This car has a trunk.";
    } else {
        echo "This car has no trunk.";
    }
?>

Of course, you must declare an instance so that you can use class constants outside the class.

강좌로 돌아가기