Mis-understanding object extension

Viewed 27

Consider the code:

    class A {
        function x(): string { return 'X'; }
        function dump(): void {
            error_log('In A: ' . $this->x());
        }
    }
    class B extends A {
        function x(): string { return 'XXX'; }
        function dump(): void {
            error_log('In B: ' . $this->x());
            parent::dump();
        }
    }
    $a = new A();
    $b = new B();
    $a->dump();
    $b->dump();

This results in:

   In A: X
   In B: XXX
   In A: XXX

, where I would expect the result to be:

   In A: X
   In B: XXX
   In A: X

What is it that I do not understand?

1 Answers

The logic seems correct. You've overridden the method, and are calling it within the context of B still.

If you want A to use its own version of the method, you can use this:

error_log('In A: ' . self::x());

Related