PHPGangsta - Der praktische PHP Blog

PHP Blog von PHPGangsta


Archive for the ‘late static binding’ tag

PHP 5.3 Feature: Late static binding (LSB)

with 9 comments

PHP 5.3 brachte unter anderem auch Late-Static-Binding (LSB). Ich würde tippen, dass einige von euch wissen was das ist, aber nur sehr wenige von euch dieses Feature bisher benötigt und eingesetzt haben. Ich möchte hier zwei kleine Beispiele zeigen, an dem klarer wird, wofür LSB benötigt wird:

class ClassA {
    public static function getName() {
        return self::name();
    }

    public static function getNameLSB() {
        return static::name();
    }

    public static function name() {
        return 'ClassA';
    }
}

class ClassB extends ClassA {
    public static function name() {
        return 'ClassB';
    }
}

echo ClassB::getName();       // ClassA
echo ClassB::getNameLSB();    // ClassB

Je nachdem ob self:: oder static:: genutzt wird, wird einmal die Elternmethode und einmal die Kindmethode aufgerufen. self:: bindet sich früh (beim Kompilieren) an seine Klasse, static:: erst bei der Ausführung (dann an die Kindklasse).

Weiterlesen »

Written by Michael Kliewe

April 17th, 2011 at 2:44 pm

Posted in PHP

Tagged with , , , ,