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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top