开发者

ReflectionClass cast to "normal" Class

I have a class TableData with two magic methods. One is the constructor and the other is the __call method.

I have realized the invoke with following code:

$class = new R开发者_JAVA百科eflectionClass('TableData');
$class->newInstanceArgs($parArray);

It work great. But now I want to use my magic method. So I call $class->getData(), but it doesn't work. I get the error, that I called an undefined method.

I tried to use ReflectionMethod and invoke, but it doesn't work again.

Is there no way to cast the ReflectionClass Object to my TableData class?

Thanks for advice!


You can't call the method on the instance of ReflectionClass. You have to call the method on the instance of your (reflected) original class.

$class    = new ReflectionClass('TableData');
$instance = $class->newInstanceArgs($parArray);
$instance->getData();


What about first getting the ReflectionClass :

class MyClass {
  public function __call($method, $args) {
    var_dump($method);
  }
}

$reflectionClass = new ReflectionClass('MyClass');

And, then, instanciating the class :

$class = $reflectionClass->newInstanceArgs();

To call your method on that $class object :

$class->getData();

And you'll get the expected result :

string 'getData' (length=7)

i.e. you have to call your methods on what is returned by `newInstanceArgs`, and not on the `ReflectionClass` itself.


I wonder why you are using Reflection here at all. Maybe you better want to modify your constructor to accept an array?

Reasons not to use Reflection are slowness and unreadability: This is much easier to use and understand:

$instace = new TableData($parArray);

Than this:

$class    = new ReflectionClass('TableData');
$instance = $class->newInstanceArgs($parArray);

So, if you want your constructor to handle both an array as argument and a list of arguments, you can use func_get_args:

class TableData {
    public function __constructor() {
        if (func_num_args() != 1 || !is_array($params = func_get_arg(0))) {
            $params = func_get_args();
        }

        // now the args are in $params either way
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜