سؤال

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?

هل كانت مفيدة؟

المحلول

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'
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top