简体   繁体   中英

Inconsistent output for PHP ReflectionMethod invoke() in PHPUnit

I came across a strange case when using php class reflection in PHPUnit. Following is how I do in straight class, it produces "ChildClass" from get_called_class(), as I expected:

class ParentClass {
    static function funcA() {
        echo get_called_class() . PHP_EOL;
    }
}

class ChildClass extends ParentClass {
}

class MyTest {
    public function test() {
        $reflectionClass = new ReflectionClass('ChildClass');
        var_dump($reflectionClass);
        $reflectionClass->getMethod('funcA')->invoke(null);
    }
}

$object = new MyTest;
$object->test();

It outputs:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "ChildClass"
}
ChildClass

But if I wrap that in a PHPUnit test case, the get_called_class() echo "ParentClass". It definitely changed behavior of invoking method on Reflection class. Did I miss anything in PHPUnit, or PHP ReflectionClass itself?

class MyTest extends PHPUnit_Framework_TestCase {
    public function testReflection() {
        $reflectionClass = new ReflectionClass('ChildClass');
        var_dump($reflectionClass);
        $reflectionClass->getMethod('funcA')->invoke(null);
    }
}

Here is the output, notice the last line, it shows "ParentClass"

PHPUnit 3.7.28 by Sebastian Bergmann.

.class ReflectionClass#221 (1) {
  public $name =>
  string(10) "ChildClass"
}
ParentClass

Thanks to @zerkms to pointing out the obvious diff from the output. I tested it again with different PHP versions. It has described problem with 5.3.3, but not with 5.5.3. That's probably the reason PHPUnit site has this line, "PHPUnit 3.7 requires PHP 5.3.3 (or later), but PHP 5.5.1 (or later) is highly recommended."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM