gpt4 book ai didi

PHP 继承和静态方法和属性

转载 作者:IT王子 更新时间:2023-10-29 00:03:41 24 4
gpt4 key购买 nike

在 PHP 中不能继承静态属性和方法是否安全?几个例子会有所帮助。

最佳答案

没有。这不是真的。 Static Methods and properties会得到 inherited与非静态方法和属性相同,并遵守相同的 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

最后两个是显着的区别。在基类中增加继承的静态属性也会在所有子类中增加它,反之亦然。

关于PHP 继承和静态方法和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7298359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com