views:

65

answers:

2

Hi everyone,

this time, I'm facing a really weird problem. I've the following code:

$xml = simplexml_load_file($this->interception_file);
foreach($xml->children() as $class) {
    $path = str_replace('__CLASS_DIR__',CLASS_DIR,$class['path']);
    if(!is_file($path)) {
       throw new Exception('Bad configuration: file '.$path.' not found');
    }
    $className = pathinfo($path,PATHINFO_FILENAME);
    foreach($class as $method) {
       $method_name = $method['name'];
       $obj = new $className();
       var_dump(in_array($method_name,get_class_methods($className)));exit;
       echo $obj->$method_name();### not a method ???
    }
}

As you can see, I get the class name and method name from an XML file. I can create an instance of the class without any problem. The var_dump at the end returns true, that means $method_name (which has 2 optional parameters) is a method of $className.

BUT, and I am pretty sure the syntax is correct, when I try: $obj->$method_name() I get:

Fatal error: Method name must be a string

If you have any ideas, pleaaaaase tell me :) Thanks in advance, Rolf

+1  A: 

The issue you are having is probably that $method_name is not a string, but it contains a method to convert it to a string (__toString()).

As in_array by default don't do strict type comparisons you will find that $method_name is probably coveted to a string and then compared with the method names, which would explain why the var_dump outputs true.

You should be able to confirm this by checking the type of $method_name

echo gettype($method_name);

If it isn't a string the solution is to case the variable to a string and then use that to call the function.

$obj->{(string)$method_name}();
Yacoby
hey hey hey! that's a bingo! :Dindeed, $method_name was an object, and the strict comparison with in_array returns false. Thanks a lot, long live Yacoby!
Rolf
A: 

It's better to use the call_user_func function instead of $obj->$method_name() to call the method.

echo call_user_func(array($className, $method_name));
Petr Peller