문제

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