Reputation: 11020
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!
Upvotes: 4
Views: 1687
Reputation: 401022
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)
Upvotes: 2
Reputation: 101936
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
}
}
Upvotes: 0
Reputation: 83622
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();
Upvotes: 11