Sarfraz Sarfraz - 4 months ago 14
PHP Question

What exactly are late static bindings in PHP?

What exactly are late static bindings in PHP?

Answer

As of PHP 5.3.0, PHP implements a feature called late static binding which can be used to reference the called class in the context of static inheritance.

Late static binding tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. It was decided not to introduce a new keyword, but rather use static that was already reserved.

Let's see an example:

<?php
    class Car
    {
        public static function run()
        {
            return static::getName();
        }

        private static function getName()
        {
            return 'Car';
        }
    }

    class Toyota extends Car
    {
        public static function getName()
        {
            return 'Toyota';
        }
    }

    echo Car::run(); // Output: Car
    echo Toyota::run(); // Output: Toyota
?>

late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non-static method calls, it is the class of the object.

A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call().

The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.