tags:

views:

37

answers:

3

Hello,

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 ReflectionClass('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!

+4  A: 

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();
Stefan Gehrig
+1  A: 

What baout 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.

Pascal MARTIN
A: 

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
    }
}
nikic
I used because the number of arguments is not even the same.I had from 5 arguments til 15 arguments so I found the solution with Reflection better.
H3llGhost