首页 > 解决方案 > PHP interface in extended class not recognized as instance

问题描述

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.

标签: phpoopinterfaceextendsinstanceof

解决方案


getX()方法不返回任何数据所以值$xnull;有一个I接口的对象实例,你需要把它放在return $this方法中getX()


推荐阅读