Difference between `self` and `static` in PHP

In PHP, static refers to a static property or method of a class, which can be accessed without creating an instance of the class. A static property or method is shared among all instances of the class, meaning that any changes to the static property or method will be reflected in all instances of the class.

self is a keyword that refers to the current class within the context of a class method or a class member access. It can be used to access static properties and methods, as well as constants and non-static methods, of the current class.

Here is an example that demonstrates the difference between static and self:

class Example
{
    public static $staticProperty = 'static property';
    public $nonStaticProperty = 'non-static property';

    public static function staticMethod()
    {
        return 'static method';
    }

    public function nonStaticMethod()
    {
        return 'non-static method';
    }
}

// Accessing static property and method using static keyword
echo Example::$staticProperty; // Outputs 'static property'
echo Example::staticMethod(); // Outputs 'static method'

// Accessing non-static property and method using self keyword
$example = new Example();
echo self::$nonStaticProperty; // Outputs 'non-static property'
echo self::nonStaticMethod(); // Outputs 'non-static method'

In this example, the static keyword is used to access the $staticProperty and staticMethod of the Example class, while the self keyword is used to access the $nonStaticProperty and nonStaticMethod of the class.

It’s worth noting that self can only be used within the context of a class, while static can be used to access static properties and methods from outside the class as well.