Zend PHP 7 Certification – OOP – Late Static Binding

This post covers the Late Static Binding section of the OOP chapter when studying for the Zend PHP 7 Certification.

Late static binding is a feature introduced in PHP 5.3 that can be used to reference the called class in a context of static inheritance.

Whenever keywords such as self or __CLASS__ are used, they refer to the class in which the function belongs.

This means that self does not follow the rules of inheritance and always resolves to the class in which it is used.

Therefore if you create a method in a parent class and call it from a child class, self will not reference the child as you might expect.

<?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(); // Outputs: A

Late static bindings resolves this issue by using the static keyword, which was not a new keyword introduced but an original one reserved already by PHP.

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

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

B::test(); // Outputs: B

To summarise, with self, the context is the one where you defined the method originally. When using static, it’s the one you’re calling it from.

Late static bindings’ resolution will stop at a fully resolved static call with no fallback i.e. using Class::method(). On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.

<?php
class A {
    public static function foo() {
        static::who();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}

class B extends A {
    public static function test() {
        A::foo();
        parent::foo();
        self::foo();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}
class C extends B {
    public static function who() {
        echo __CLASS__."\n";
    }
}

C::test();

// Outputs:
A
C
C

View the other sections:

Note: This article is based on PHP version 7.0.