What is the difference between self and static in PHP?

The main differences is that static allows late static bindings. One of the most useful scenarios that I found was for creating Base classes for Singleton Classes:

class A { // Base Class
    protected static $name = '';
    protected static function getName() {
        return static::$name;
    }
}
class B extends A {
    protected static $name = 'MyCustomNameB';
}
class C extends A {
    protected static $name = 'MyCustomNameC';
}
echo B::getName(); // MyCustomNameB
echo C::getName(); // MyCustomNameC

Using return static::$name in the Base class will return what was statically attached when it was extended.
If you were to use return self::$name then B::getName() would return an empty string as that is what is declared in the Base class.

Comments

Popular posts from this blog

Basic Terminology

What is normalization in DBMS?

Object oriented programming concepts in PHP