문제

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