5

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?

2
  • I found a reason: As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. (at: php.net/manual/en/function.get-class.php#77698) However I still need a solution... Commented Jun 24, 2010 at 4:13
  • Just for the record, this is solved in PHP 5.3 (as BoltClock suggested) using: return static::multi($a, $b); instead of using "self" at the parent class. Commented Jun 24, 2010 at 5:03

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes that is what I read... Thank you anyway! (I should update PHP...)
-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: I see, my bad. I've corrected my answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.