views:

273

answers:

3

Hello,

What exactly is late-static binding in PHP?

+3  A: 

There's a doc for that:

PHP: Late Static Bindings

Don Neufeld
+12  A: 

You definitely need to read Late Static Bindings in the PHP manual. However, I'll try to give you a quick summary.

Basically, it boils down to the fact that the self keyword does not follow the rules of inheritance. self always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, self will not reference the child as you might expect.

Late static binding introduces a new use for the static keyword, which addresses this particular shortcoming. When you use static, it represents the class where you first use it, ie. it 'binds' to the runtime class.

Those are the two basic concepts behind it. The way self, parent and static operate when static is in play can be subtle, so rather than go in to more detail, I'd strongly recommend that you study the manual page examples. Once you understand the basics of each keyword, the examples are quite necessary to see what kind of results you're going to get.

zombat
A: 

For example:

abstract class Builder {
    public static function build() {
        $class = get_called_class();
        return new $class();
    }
}

class Member extends Builder {
    public function who_am_i() {
         echo 'Member';
    }
}

Member::build()->who_am_i();
Petah