1

Given the following Code:

class A {
    public static function one() {
        return "results from Parent::one";
    }
    public function two() {
        return "Parent::two got info: ".self::one();
    }
}

class B extends A {
    public static function one() {
        return "results from child::one";
    }
}

$a=new B();
print "calling two I get: ". $a->two()."\n";
print "calling one I get: ". $a->one()."\n\n";

I get the following results:

calling two I get: Parent::two got info: results from Parent::one

calling one I get: results from child::one

I expected the first result above to be:

calling two I get: Parent::two got info: results from child::one

It seems that while overrides work, they do not work recursively, only in a direct call from the child. Is there a way to assure that when a child class accesses a method from the parent, the parent methods reference the overridden methods when they exist?

Thanks

Community
  • 1
  • 1
JoEng
  • 13
  • 2
  • 1
    `$this->one()` instead of `self::one()` – Patrick Q Oct 31 '19 at 21:20
  • 2
    It's a static method, so you should use `static::one()` for [late static binding](https://www.php.net/manual/en/language.oop5.late-static-bindings.php). Do not use `$this` to call static methods. – Alex Barker Oct 31 '19 at 21:23
  • @AlexBarker You should give some reasoning if you're going to make a definitive statement like "Do not use `$this` to call static methods." In this example, `two()` is not a static function, so within that function we know that an instantiated object is already being used, so I don't see anything inherently _wrong_ with using `$this` here. – Patrick Q Oct 31 '19 at 21:29
  • @PatrickQ, I don't believe it requires an explanation as it is in violation of the language constructs. Indeed that method is not static, my mistake. – Alex Barker Oct 31 '19 at 21:54
  • Thanks to both of you, I needed both solutions as I had the same problem in some static functions. I cannot flag this as the answer since it was in the comments and not an answer. Not sure if you care, but if one of you want the credit, put it in the answer section and I'll flag it... otherwise I'll mark forsvunnet's as he has it in the answer section. Wish I'd known to google "static"! – JoEng Oct 31 '19 at 22:47
  • Possible duplicate of [How do I call a static child function from parent static function?](https://stackoverflow.com/questions/6678466/how-do-i-call-a-static-child-function-from-parent-static-function) – Patrick Q Nov 01 '19 at 12:07

1 Answers1

0

You're probably looking for late bindings. Simply changing from self::one() to static::one() should do the trick.

return "Parent::two got info: ".static::one();
forsvunnet
  • 1,238
  • 10
  • 17