0

I have an abstract class A which is extended by class B which implements the interface I.

abstract class A {
  public function test(){
    return $this->getX();
  }
  abstract protected function getX();
}

class B extends A implements I {
  public function Test() {
    $x = this->getX();
    if (!$x instanceof I) {
      throw new RuntimeException("not an instance of I");
    }
  }

  public function getX() {
    $aCoordinates = array('x' => 1, 'y' => 4, 'z' => 5); 
    return $aCoordinates;
  }
}

interface I {}

The RuntimeException is always thrown, despite $x is an instance of I. Anyone an idea why this happens?

getX() returns an array. getX() is just an example for a function returning an array.

8
  • If I look at this correctly, $x here will be set to 10, which is not an instance of I, but just a normal integer, right? Commented Nov 18, 2018 at 22:52
  • I've updated my example code. Actually $x ist just the result of getX() Commented Nov 18, 2018 at 22:55
  • 2
    What does getX return? Whatever it is, it's not an instance of I either Commented Nov 18, 2018 at 22:58
  • @Jake we need to see what getX() returns to help you. Commented Nov 18, 2018 at 22:58
  • 1
    @Jake if $x = getX(), therefore $x = array. An array is not an instance of your interface. This is why your exception is being thrown. Commented Nov 18, 2018 at 23:10

1 Answer 1

1

The getX() method doesn't return any data So the value of $x is null; to have an object instance of I interface you need to put return $this in getX() method.

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

2 Comments

actually it does. I just forgot it in the example code.
Now getX() returns an array and of course its not instance of I interface. You need put return $this; instead of return $aCoordinates;

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.