문제

I don't get how this late static binding works.

abstract class A{

  final public static function doprint(){
    print get_called_class() . '<br>';
  }


  public static function wrapper(){
    self::doprint();
    static::doprint();
  }

}

class A2 extends A{}    

A2::wrapper();

get_called_class() prints A2 in both cases, even when I called the doprint method with self. why?

도움이 되었습니까?

해결책

get_called_class() always returns the class you actually call. You call A2:: so it's A2.

On my site there's a tutorial with an LSB singleton abstract class. I'm not linking here because there's always a zombie vigilante that comes and removes the links without even looking. But it's in my description.

The catch with LSB is that a method in A can call a method in B which can call a method in A back. See this example:

header('Content-Type: text/plain'); // Pretty text output
// LSB Parent
class A {
    // NOLSB: Will call Current Class method
    static public function TriggerSelf() {
        self::OverrideMe();
    }
    // LSB: Will call Inheriting Class method (or Current if none Inherits)
    static public function TriggerStatic() {
        static::OverrideMe();
    }
    // Method to Override
    static public function OverrideMe() {
        echo 'A here', PHP_EOL;
    }
}

// LSB Child
class B extends A {
    // Override by LSB
    static public function OverrideMe() {
        echo 'B here', PHP_EOL;
    }
}

A::TriggerSelf(); // <- NO LSB
A::TriggerStatic(); // <- LSB (but not inheritance)

B::TriggerSelf(); // <- NO LSB
B::TriggerStatic(); // <- LSB (with inheritance, so it works)

See how B::TriggerStatic() allows A to call a B method while B::TriggerSelf() calls a A method. That's LSB. Parent class static methods can call child class static methods. It's pretty much static abstracts :)

Study the example, it'll make sense.

다른 팁

I think get_called_class() is telling you which class was called, and its output is correct.

Late static binding allows the self context to bubble up, so methods defined higher can operate on the called method's object.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top