PHP 继承和静态方法和属性

2022-08-30 22:07:58

可以肯定地说,静态属性和方法不能在PHP中继承吗?几个例子会有所帮助。


答案 1

不。那不是真的。静态方法和属性将获得与非静态方法和属性相同的继承,并遵循相同的可见性规则:

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

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


答案 2

不(显然我看不到问题中没有)。 和静态方法和属性将继承,正如您期望的那样:publicprotected

<?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();
?>

静态属性和方法遵循可见性继承规则,如本代码段所示。


推荐