User Tools

Site Tools


php:late_static_binding

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

php:late_static_binding [2013/03/16 17:40] (current)
Line 1: Line 1:
 +==== 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.//
 +
 +
 +<code php | 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();​
 +</​code>​
 +
 +It will print an unexpected result:
 +
 +<​code>​
 +Book is available, method Book::​get_status()
 +Book is available, method Book::​get_status()
 +</​code>​
 +
 +The right way is to replace **self** with **static** in this case:
 +
 +<code php | Using static>
 +...
 +    public static function status()
 +    {
 +        echo static::​get_status();​
 +    }
 +...
 +</​code>​
 +
 +The result is now the expected one:
 +
 +<​code>​
 +Book is available, method Book::​get_status()
 +Book is NOT available, method BookNotAvailable::​get_status()
 +</​code>​
php/late_static_binding.txt ยท Last modified: 2013/03/16 17:40 (external edit)