PHP – static:: vs self::

What is the difference between static:: and self:: in a PHP object oriented reference?

The simple answer is that most of the time, they are the same.  There is a small difference between the two that many PHP developers and programmers do not know.

static::, which was introduced in PHP 5.3, uses “late static bindings”.  In other words, the most recent one.  This is important when dealing with inheritance and overriding methods and members.

You can read about Late Static Bindings in the PHP manual.

self:: on the other hand references the class that it is in.

Here is some sample code that illustrates this:

This code will have the following output:

In this example, class Baz extends class Bar, which extends class Foo.  Calling Baz::valueFoo(), which is not overridden in either class Baz nor Bar, is executed in class Foo.

self::$x prints out the value of 1234.  Remember self::$x references the class that the code is written in; in this case, Foo.

static::$x prints 4321, as that was the latest override to $x found in class Baz.

The value of $x from class Bar is missing from the print out, as it is not the first nor the last.

I hope that is clear!  Now lets muddy the waters a little.

The output is this:

Perfectly clear, right?  It might not be.  So here it is with some annotations:

self:: resolves to the class that the self:: keyword is in.

static:: resolves to the latest class to override the method or member.