User Tools

Site Tools


php:late_static_binding

Late Static Binding

Sept 2012

From php manual:

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.
More precisely, 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.

Using self

class Book
{
    public static function status()
    {
        echo self::get_status();
    }
 
    public static function get_status()
    {
        return "Book is available, method Book::get_status() \n";
    }
 
}
 
class BookNotAvailable extends Book
{
    public static function get_status()
    {
        return "Book is NOT available, method BookNotAvailable::get_status() \n";
    }
}
 
$book = Book::status();
$book_not = BookNotAvailable::status();

It will print an unexpected result:

Book is available, method Book::get_status()
Book is available, method Book::get_status()

The right way is to replace self with static in this case:

Using static

...
    public static function status()
    {
        echo static::get_status();
    }
...

The result is now the expected one:

Book is available, method Book::get_status()
Book is NOT available, method BookNotAvailable::get_status()

php/late_static_binding.txt · Last modified: 2013/03/16 17:40 (external edit)