PHP Reflection with two calls

2019-09-14 23:35发布

问题:

I am trying to archive some reflection in php. How can i make something like that. With my code i am getting following error:

Undefined property: A::$getB()->getStr()

class B{
    public function getStr(){
        return 'str';
    }
}
class A{
    public function getB(){
        return new B();
    }
}

$a = new A();
$method = 'getB()->getStr()';
echo($a->$method);

回答1:

You have to split the call chain to the single calls

$getB = "getB";
$str = "getStr";
$a = new A();
echo $a->$getB()->$str();


回答2:

You should definitely use ReflectionClass and ReflectionMethod instead of string wizardy.