Elementor调试提示Undefined variable $out但功能正常问题求助
问题根因
报错原因很直接:你在content方法的foreach循环中用$out .=拼接字符串时,没有提前初始化$out变量。
功能正常是因为PHP对未定义的拼接变量会默认当作空字符串处理,不会中断执行,但会抛出E_NOTICE级别的调试提示,也就是你看到的那条Undefined variable警告。
另外你这段代码还有三个隐藏问题,之后大概率也会触发报错或者逻辑异常:
- 循环第一行调用
tmaddon_bg_images时传入的$settings['img_size'],在当前方法作用域内没有定义,也没有作为参数传入 - nofollow属性的判断逻辑写错了:现在的逻辑是只要有链接就加
rel=nofollow,和用户后台是否勾选nofollow选项无关 - HTML属性值没加引号,特殊场景下会出现渲染异常
修复方案
在foreach循环开始前先给$out赋初始空值,同时修正上面提到的隐藏问题即可,修复后的代码如下:
private function content($content,$disp) { // 初始化输出变量,解决未定义变量警告 $out = ''; // 请根据实际业务逻辑补全$settings的取值,比如从类属性读取、或者作为方法参数传入 foreach ($content as $item){ $img = tmaddon_bg_images($item['img']['id'],$settings['img_size']); $title = $item['title'] ? '<span class="tm-title"><p>'.$item['title']. '</p></span>' : ''; $subtitle = $item['subtitle'] ? '<span class="tm-subtitle"><p>'.$item['subtitle']. '</p></span>' : ''; $label_text = $item['label-text'] ? '<span>'.$item['label-text']. '</span>' : ''; $icon = $item['icon'] ? '<div class="read-more-btn link link--arrowed"> <svg class="arrow-icon" xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="9 9 32 32"> <g fill="none" stroke="" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10"> <circle class="arrow-icon--circle" cx="25" cy="25" r="15.12"></circle> <i class="arrow-icon--arrow '.$item['icon'].'"></i> </g> </svg> </div>' : ''; $carcls = $disp == 'carousel' ? 'swiper-slide' : $disp; $url = $item['url']['url']; $ext = $item['url']['is_external']; $nofollow = $item['url']['nofollow']; $url = ( isset($url) && $url ) ? 'href="'.esc_url($url).'"' : ''; $ext = ( isset($ext) && $ext ) ? 'target="_blank"' : ''; $nofollow = ( isset($nofollow) && $nofollow ) ? 'rel="nofollow"' : ''; $link = trim($url.' '.$ext.' '.$nofollow); $btn = $url ? '<a '.$link.' class="fullink"></a>' : ''; $out .= ' <div class="items '.$carcls.'"> <div class="item-wrap"> <div '.$img.' class="item-image lazyload"> '.$btn.' <div class="label-text">'.$label_text.'</div> <div class="item-content"> '.$icon.$title.$subtitle.' </div> </div> </div> </div> '; } return $out; }
修复后就算传入的$content是空数组,方法也会正常返回空字符串,不会抛出任何调试警告。
内容的提问来源于stack exchange,提问作者WordPresser
相关产品推荐
相关产品推荐

