Php OOP - Examples and Tips | Drupal 8

Php OOP - Examples and Tips

Submitted by editor on Tue, 03/28/2017 - 12:18
Question

What is the Different between self:: and static ?

Different between self:: and static (Late Static Bindings)

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined.
Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime. Basically, a keyword that would allow you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.

Example: (self::)
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}
class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}
B::test();

// Return A

 

Example: (static::)
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}
class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}
B::test();

// Return B

Source : http://php.net/manual/en/language.oop5.late-static-bindings.php

Tags

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.