PHP继承和静态方法和属性

时间:2011-09-04 09:42:17

标签: php inheritance static

是否可以安全地说静态属性和方法不能在PHP中继承?一些例子会有所帮助。

2 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分:5)

否(显然我在问题中看不到)。 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();
?>

静态属性和方法遵循visibility中所述的inheritancethis snippet规则。