Question

See the following example (taken from a previous question):

    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'

Is there a way such that when B calls test(), self will call B's getVar() function?

Était-ce utile?

La solution

What you're talking about is called Late Static Binding and it's available since PHP 5.3. All you need to do is use the word static instead of self:

class ClassA {
    public static function test() { return static::getVar(); }
}
class ClassB  extends ClassA {
    public static function getVar() { return 'B'; }
}

echo ClassB::test(); // prints 'B'
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top