Home » Php » php – Getting class constant inside class

php – Getting class constant inside class

Posted by: admin July 12, 2020 Leave a comment

Questions:

What’s the difference between self::CONSTANT_NAME and static::CONSTANT_NAME?

Is calling constant via static:: only 5.3 feature?

How to&Answers:

The difference is pretty much what late static bindings are all about.

Short explanation:

self:: will refer to the class type inside which the code using self:: is written.

static:: will refer to the class type of the actual object that on which the code using static:: is being executed.

This means that there’s only a difference if we are talking about classes in the same inheritance hierarchy.

Answer:

When you use static::NAME it’s a feature called late static binding (or LSB). More information about this feature is at the php.net documentation page of LSB: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

An example is this use case:

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

This outputs A, which is not always desirable. Now replacing self with static creates this:

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

And, as you might expect, it ouputs “B”