0

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

4

2 に答える 2

2

あなたが抱えている問題は、おそらく $method_name が文字列ではなく、文字列 ( __toString()) に変換するメソッドが含まれていることです。

in_array はデフォルトで厳密な型比較を行わないため、おそらく文字列に切望され、メソッド名と比較されることがわかります。これにより、出力が true$method_nameである理由が説明されます。var_dump

のタイプをチェックすることで、これを確認できるはずです。$method_name

echo gettype($method_name);

文字列でない場合の解決策は、変数を文字列に変換し、それを使用して関数を呼び出すことです。

$obj->{(string)$method_name}();
于 2010-04-23T11:54:47.153 に答える
1

$obj->$method_name()メソッドを呼び出すのではなく、call_user_func関数を使用することをお勧めします。

echo call_user_func(array($className, $method_name));
于 2010-04-23T12:04:00.093 に答える