动态方法调用的奇怪问题
这次,我面临着一个非常奇怪的问题。我有以下代码:
$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 ???
}
}
如您所见,我从 XML 文件中获取类名和方法名。 我可以毫无问题地创建该类的实例。最后的var_dump返回true,这意味着$method_name(有2个可选参数)是$className的方法。
但是,我很确定语法是正确的,当我尝试: $obj->$method_name() 我得到:
致命错误: 方法名称必须是字符串
如果您有任何想法,请告诉我:) 提前致谢, 罗尔夫
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到的问题可能是 $method_name 不是字符串,但它包含一个将其转换为字符串的方法 (
__toString()
)。由于 in_array 默认情况下不进行严格的类型比较,您会发现
$method_name
可能会被渴望为字符串,然后与方法名称进行比较,这可以解释为什么var_dump
> 输出 true。您应该能够通过检查 $method_name 的类型来确认这一点。
如果它不是字符串,解决方案是将变量设置为字符串,然后使用它来调用函数。
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 thevar_dump
outputs true.You should be able to confirm this by checking the type of
$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.
最好使用 call_user_func 函数而不是
$obj->$method_name()
来调用该方法。It's better to use the call_user_func function instead of
$obj->$method_name()
to call the method.