Domanda

I understand how late static binding works, but I can't seem to come up with a time when I'd use it. The examples on the PHP site are nice, but don't show any kind of realistic usage. I'm just wondering if there are any examples of when LSB is absolutely necessary to solve a problem, or when it helps simplify potentially complicated code.

È stato utile?

Soluzione

It can be used to create static factory patterns, using late static binding with static method overloading to prevent requiring additional cumbersome factory classes, such as:

class MyObject {

    public static function createInstance($typeA = true) {
        if ($typeA) {
            return static::createInstanceA();
        }else{
            return static::createInstanceB();
        }
    }

    protected static function createInstanceA() {
        return new MyObject(...);
    }

    protected static function createInstanceB() {
        return new MyObject(...);
    }
}


class MyObjectDebug extends MyObject {

    protected static function createInstanceA() {
        return new MyObjectDebug(...);
    }
}

if you like that sort of thing, of course.

Altri suggerimenti

LSB is important when extending classes. It allows you to use static:: to reference a member of the called class, whereas self:: specifically references the class it is used. Basically, LSB lets you override static methods in the base class.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top