Difference between self::$bar and static::$bar in PHP


In PHP, self::$bar and static::$bar are used to access static properties within a class. However, there is a difference between the two.

self::$bar refers to the static property $bar defined in the current class. It does not matter if the method is called from a child class, it will always refer to the static property in the current class.

Example:

class Foo {
    public static $bar = 'foo';

    public static function getBar() {
        return self::$bar;
    }
}

class Baz extends Foo {
    public static $bar = 'baz';
}

echo Foo::getBar(); // Output: foo
echo Baz::getBar(); // Output: foo

In the above example, self::$bar always refers to the static property $bar defined in the Foo class, even when the getBar() method is called from the Baz class.

On the other hand, static::$bar refers to the static property $bar defined in the class where the method is called. If the method is called from a child class, it will refer to the static property in the child class.

Example:

class Foo {
    public static $bar = 'foo';

    public static function getBar() {
        return static::$bar;
    }
}

class Baz extends Foo {
    public static $bar = 'baz';
}

echo Foo::getBar(); // Output: foo
echo Baz::getBar(); // Output: baz

In the above example, static::$bar refers to the static property $bar defined in the class where the getBar() method is called. When the method is called from the Baz class, it refers to the static property in the Baz class.

In summary, self::$bar always refers to the static property in the current class, while static::$bar refers to the static property in the class where the method is called.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.