【问题标题】:PHP - ReflectionClass - getMethods only for current classPHP - ReflectionClass - getMethods 仅适用于当前类
【发布时间】:2015-09-21 14:22:07
【问题描述】:

目前我尝试将 PHPUnit 集成到我的项目中。 为了确保随着时间的推移 100% 的测试覆盖率,我想检查在 testclass 中是否存在要测试的类中的所有方法。 所以我想我可以写一些像

class MyClassTest extends PHPUnit_Framework_TestCase {

    private function _getClassFunctions($class) {
        $class = new ReflectionClass($class);
        return $class->getMethods();
    }

    public function testCompareFunctionCount() {
        $this->assertEquals($this->_getClassFunctions('MyClass'), $this->_getClassFunctions(__CLASS__));
    }
}

然而,ReflectionClass::getMethods() 似乎不仅计算类本身的方法,还计算所有扩展类。 有没有办法防止这种行为?还是我完全错了?我在较早的文章中读到 ReflectionClass::getMethods() 在较旧的 PHP 版本上无法正常工作,但我认为它现在可能已修复(这些文章已有 4 年以上的历史了......)
我使用 PHP 5.4.5。

【问题讨论】:

    标签: php


    【解决方案1】:

    你必须自己做一些工作:

    private function _getClassFunctions($className) {
       $class = new ReflectionClass($className);
       $result = array();
       foreach($class->getMethods() as $method) {
          if ($method->class == $className) {
             $result[]=$method;
          }
       }
       return $result;
    }
    

    比较 $method->class$className 将结果缩小到仅包含在相关类中的方法。

    【讨论】:

    • 这正是我所需要的。非常感谢你! :)
    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多