Late static binding

suggest change

In PHP 5.3+ and above you can utilize late static binding to control which class a static property or method is called from. It was added to overcome the problem inherent with the self:: scope resolutor. Take the following code

class Horse {
    public static function whatToSay() {
         echo 'Neigh!';
    }

    public static function speak() {
         self::whatToSay();
    }
}

class MrEd extends Horse {
    public static function whatToSay() {
         echo 'Hello Wilbur!';
    }
}

You would expect that the MrEd class will override the parent whatToSay() function. But when we run this we get something unexpected

Horse::speak(); // Neigh!
MrEd::speak(); // Neigh!

The problem is that self::whatToSay(); can only refer to the Horse class, meaning it doesn’t obey MrEd. If we switch to the static:: scope resolutor, we don’t have this problem. This newer method tells the class to obey the instance calling it. Thus we get the inheritance we’re expecting

class Horse {
    public static function whatToSay() {
         echo 'Neigh!';
    }

    public static function speak() {
         static::whatToSay(); // Late Static Binding
    }
}

Horse::speak(); // Neigh!
MrEd::speak(); // Hello Wilbur!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents