从PHP5.6升级至7.1遇Array to string conversion报错求解决
PHP 7.1升级后"Array to string conversion"错误修复方案
这个问题我之前帮同事排查过,核心原因是PHP 7.0及以上版本对变量解析的优先级做了调整,和PHP 5.6的执行逻辑不一样了。
你的代码里$this->$functions[$i]这个写法,在PHP 5.6中会先解析$functions[$i]拿到具体的方法名,再调用$this对应的方法;但到了PHP 7.x,它会优先尝试解析$this->$functions——而$functions是一个数组,PHP需要把它转成字符串当作属性名,这就直接触发了"Array to string conversion"的警告。
解决起来很简单,有两种清晰的写法可以选:
方案一:用花括号明确解析优先级
通过花括号包裹数组元素,强制PHP先解析出方法名再调用:
// 原错误写法 $template = $this->$functions[$i]($name, $value); // 修改后 $template = $this->{$functions[$i]}($name, $value);
方案二:先存储方法名到临时变量
这种写法可读性更强,也能避免优先级歧义:
$method = $functions[$i]; $template = $this->$method($name, $value);
额外优化建议
你的while循环没有数组边界判断,如果所有方法都返回false,$i会一直递增,最终会触发"Undefined offset"的越界错误。可以加上边界检查完善代码:
protected function getobjectTemplate($name, $value) { $template = false; $functions = [ 'getObjectFormClientTemplate', 'getObjectFormTemplate', 'getObjectAirformTemplate', 'getTypeAirformTemplate', 'getAirfileTemplate', 'getTextAirformTemplate', ]; $i = 0; $totalMethods = count($functions); // 增加数组边界判断,避免越界 while (!$template && $i < $totalMethods) { $template = $this->{$functions[$i]}($name, $value); ++$i; } return $template; }
内容的提问来源于stack exchange,提问作者Mathieu Mourareau
相关产品推荐
相关产品推荐

