The differance between self:: and static:: in PHP

Problem : Why would developers use self:: and static:: in PHP OO classes

Solution

Well consider the below code

class Foo
{
    protected static $bar = 1234;

    public static function instance()
    {
        echo self::$bar;
        echo "\n";
        echo static::$bar;
    }

}

Foo::instance();

The output will have no difference

 

1234

1234 

 

But actually there is a difference when using self:: and static::

slef:: is used when  you're referring to the class within which you use the keyword in this case its a static property called $bar in the Foo class itself. 

static:: is  called when you're invoking a feature called late static bindings (introduced in PHP 5.3).  So what you are doing is, you are calling late static bindings (or static properties) on whatever class in the hierarchy you called the method on. The below example will clear thing

class Foo
{
    protected static $bar = 1234;
    public static function instance()
    {
        echo self::$bar;
        echo "\n";
        echo static::$bar;
    }

}

class Bar extends Foo
{
    protected static $bar = 4321;
}

Foo::instance();

 

The output will be

 

1234

4321

 

 

Tags