How is the correct way to call a child class method from a parent class if both are static?
When I use static classes it returns the error " Call to undefined method A::multi() ", however when I use non-static methods there is no problem, for example:
//-------------- STATIC ------------------
class A {
public static function calc($a,$b) {
return self::multi($a, $b);
}
}
class B extends A {
public static function multi($a, $b) {
return $a*$b;
}
}
echo B::calc(3,4); //ERROR!!
//-------------- NON-STATIC ----------------
class C {
public function calc($a,$b) {
return $this->multi($a, $b);
}
}
class D extends C {
public function multi($a, $b) {
return $a*$b;
}
}
$D = new D();
echo $D->calc(3,4); // Returns: 12
Is there a way to call a child static method without knowing its class name?
It's only possible in PHP 5.3 and newer, with late static bindings , where PHP 5.3 is able to access static members in subclasses instead of whatever the class that self
refers to because it's resolved during runtime instead of compile-time.
Unfortunately, I don't think there's a solution for this in PHP 5.2 and older.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.