views:

62

answers:

1

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?

+4  A: 

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.

BoltClock
Yes that is what I read... Thank you anyway! (I should update PHP...)
lepe
-1 There is no inheritance of static members. There's a copy of static methods in the subclass if they're not redefined, but it's not inheritance.
Artefacto
@Artefacto: I see, my bad. I've corrected my answer accordingly.
BoltClock
I reverted the vote.
Artefacto