Is it safe to say that static properties and methods can not be inherited in PHP? a few examples will be helpful.
The static variable is used in the A and B classes, yet the method is inherited so it is actually the same code which is called. Until PHP 8.0, there would be a distinct static variable depending on which class is called.
Introduction to PHP static methods and properties PHP allows you to access the methods and properties in the context of a class rather than an object. Such methods and properties are class methods and properties. Class methods and class properties are called static methods and properties.
In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.
No. That's not true. Static Methods and properties will get inherited the same as non-static methods and properties and obey the same visibility rules:
class A {
    static private $a = 1;
    static protected $b = 2;
    static public $c = 3;
    public static function getA()
    {
        return self::$a;
    }
}
class B extends A {
    public static function getB()
    {
        return self::$b;
    }
}
echo B::getA(); // 1 - called inherited method getA from class A
echo B::getB(); // 2 - accessed inherited property $b from class A
echo A::$c++;   // 3 - incremented public property C in class A
echo B::$c++;   // 4 - because it was incremented previously in A
echo A::$c;     // 5 - because it was incremented previously in B
Those last two are the notable difference. Incrementing an inherited static property in the base class will also increment it in all the child classes and vice versa.
No (Apparently I couldn't see the not in the question). public and protected static methods and properties are inherited as you would expect them to be:
<?php
class StackExchange {
    public static $URL;
    protected static $code;
    private static $revenue;
    public static function exchange() {}
    protected static function stack() {}
    private static function overflow() {}
}
class StackOverflow extends StackExchange {
    public static function debug() {
        //Inherited static methods...
        self::exchange(); //Also works
        self::stack();    //Works
        self::overflow(); //But this won't
        //Inherited static properties
        echo self::$URL; //Works
        echo self::$code; //Works
        echo self::$revenue; //Fails
    }
}
StackOverflow::debug();
?>
Static properties and methods obey the visibility and inheritance rules as illustrated in this snippet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With