在ReflectionClass中出现未定义方法错误,但方法存在


Undefined method error in ReflectionClass but method exists

我目前正在使用phpunit进行一些单元测试。由于存在一些受保护的方法,我不得不使用Reflection Class将这些方法的可见性更改为public

初始方法被成功调用,但不知何故它被困在一个特定的方法:

Fatal error: Call to undefined method ReflectionClass::create_schema()in
/vagrant/fuelphp/fuel/app/tests/model/repository/jobpost.php on line 54

然而,通过get_method()var_dump转储方法证明它存在于类实例中:

class ReflectionMethod#2317 (2) {
  public $name =>
  string(13) 'create_schema'
  public $class =>
  string(34) 'Model_Repository_Feed'
}

然后真正令人困惑的是,我决定使用hasMethod()来查看该方法是否存在:

 52     echo "If this says 1, class exists: ".$this->_target->hasMethod('create_schema');
 53     try {
 54         $this->_target->create_schema();
 55     }

运行时的结果显示"yes it exists...."但它没有":

If this says 1, class exists: 1
Fatal error: Call to undefined method ReflectionClass::create_schema() in /vagrant/fuelphp/fuel/app/tests/model/repository/jobpost.php on line 54

说明这个方法是公共的,并且继承自abstract父类:

public function create_schema() {
    $this->create_schema_exec(self::$_real_schema_name);
  }

如何解决这个问题?

您需要获取保存该方法的类的对象,而不是反射对象。

$reflection = new ReflectionClass($className);
$object = $reflection->newInstanceWithoutConstructor();
$object->methodName();