PHP继承和静态方法和属性 [英] PHP Inheritance and Static Methods and Properties
本文介绍了PHP继承和静态方法和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以安全地说静态属性和方法不能在PHP中继承?一些例子会有所帮助。
Is it safe to say that static properties and methods can not be inherited in PHP? a few examples will be helpful.
推荐答案
没有。这不是真的。 静态方法和属性将获得继承与非静态方法和属性相同并遵守相同的可见性规则:
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.
这篇关于PHP继承和静态方法和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文