Search code examples
phpclassstaticextends

If i extend a static class in PHP, and the parent class refers to "self::", will this refer to the self in the extended class?


If i extend a static class in PHP, and the parent class refers to "self::", will this refer to the self in the extended class?

So, for example

<?php 
Class A
{
    static $var  
    public static function guess(){self::$var = rand(); return $var}
}        

Class B extends Class A
{
    public static function getVar(){return self::$var}
}

If I ran B::guess(); then B::getVar();

is the value for Var stored in A::$var or B::$var?

Thank you.


Solution

  • It's easy to test:

    class ClassA {
        public static function test(){ self::getVar(); }
        public static function getVar(){ echo 'A'; }
    }        
    
    class ClassB extends ClassA {
        public static function getVar(){ echo 'B'; }
    }
    
    ClassA::test(); // prints 'A'
    
    ClassB::test(); // also prints 'A'
    

    ... hope that helps :)