self:: vs className:: inside static className methods in PHP

With self you can use it within the class and with the "MyClass", as you have, you can reference it externally:

$instance = new Myclass();
$variable = $instance::$foo

(Note: the initial version said there was no difference. Actually there is)

There is indeed a small diference. self:: forwards static calls, while className:: doesn't. This only matters for late static bindings in PHP 5.3+.

In static calls, PHP 5.3+ remembers the initially called class. Using className:: makes PHP "forget" this value (i.e., resets it to className), while self:: preserves it. Consider:

<?php
class A {
    static function foo() {
        echo get_called_class();
    }
}
class B extends A {
    static function bar() {
        self::foo();
    }
    static function baz() {
        B::foo();
    }
}
class C extends B {}

C::bar(); //C
C::baz(); //B

Tags:

Php

Class

Static