Is it safe to say that static properties and methods can not be inherited in PHP? a few examples will be helpful.
2 Answers
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.
Comments
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.