CodeBlanks Logo Icon CodeBlanks

Accessing constants

PHP course · Intermediate · Lesson 37/115

Learn to access class constants from outside and inside with the :: operator.

Accessing constants with the :: operator

Class constants are accessed with the :: operator (scope resolution operator). From outside you write ClassName::CONSTANT.

Example: echo Circle::PI;. Here Circle is the class name, :: is the access operator, PI is the constant name. No $ sign is used.

To access from inside the class, use self::CONSTANT. self refers to the current class. Example: self::PI. This does not do late static binding like static::; it always refers to the defining class.

self:: and parent:: from inside the class

When you use a constant inside the class, write self::CONSTANT. self refers to the class that defines the method.

Example: in a Circle class, an area method uses the constant: return self::PI * $r * $r;. Here self::PI is the PI constant of the same class.

If you need to call a parent constant from a subclass, use parent::CONSTANT. parent:: refers to the parent class.

Exercise Circle class computing area with a constant

Define a Circle class with const float PI = 3.14;. Add public function area(float $r): float that does return self::PI * $r * $r. Then create $circle = new Circle() and print echo $circle->area(2) . "\n". (Expected output: 12.56)

Show example solution
float { return self::PI * $r * $r; } } then $circle = new Circle(); echo $circle->area(2) . "\n";
Example solution:
<?php
// Define a Circle class and add an area method
class Circle {
    const float PI = 3.14;
    public function area(float $r): float {
        return self::PI * $r * $r;
    }
}
$circle = new Circle();
echo $circle->area(2) . "
";

Test yourself

  1. How do you access the PI constant of Circle from outside?

    • Circle::PI
    • $circle->PI
    • Circle->PI
    • $circle::PI
    Show answer

    Circle::PI — Correct. Circle::PI accesses the class constant from outside.

  2. Access a constant from inside the class

    class Circle {
        const float PI = 3.14;
        public function area(float $r): float {
            return ____ * $r * $r;
        }
    }
    Show answer
    class Circle {
        const float PI = 3.14;
        public function area(float $r): float {
            return self::PI * $r * $r;
        }
    }
  3. Match the constant access forms

    Circle::PI
    From outside the class
    self::PI
    From inside the class
    parent::PI
    From the parent class
    static::PI
    Late binding (subclass)

All lessons in Intermediate