What is the difference between using self and static in the example below?
class Foo
{
protected static $bar = 1234;
public static function instance()
{
echo self::$bar;
echo "\n";
echo static::$bar;
}
}
Foo::instance();
produces
1234
1234
When you use
selfto refer to a class member, you’re referring to the class within which you use the keyword. In this case, yourFooclass defines a protected static property called$bar. When you useselfin theFooclass to refer to the property, you’re referencing the same class.Therefore if you tried to use
self::$barelsewhere in yourFooclass but you had aBarclass with a different value for the property, it would useFoo::$barinstead ofBar::$bar, which may not be what you intend:When you call a method via
static, you’re invoking a feature called late static bindings (introduced in PHP 5.3).In the above scenario, using
selfwill result inFoo::$bar(1234).And using
staticwill result inBar::$bar(4321) because withstatic, the interpreter takes into account the redeclaration within theBarclass during runtime.You typically use late static bindings for methods or even the class itself, rather than properties, as you don’t often redeclare properties in subclasses; an example of using the
statickeyword for invoking a late-bound constructor can be found in this related question: New self vs. new staticHowever, that doesn’t preclude using
staticwith properties as well.