PHP变量引用数组修改无效问题及批量处理select标签咨询
为什么PHP数组中存储的变量引用修改后原变量没变化?
场景说明
我用PHP渲染了一组HTML select标签,示例代码如下:
$templates = array( 'Template1', 'Template2', 'Template3', 'Template4'); $templates_dropdown = '<select required id="templates" name="admin[template_select]"> <option value="">'.__( 'Pick a template', 'textdomain' ).'</option>'; foreach( $templates as $value){ $template_value = esc_html( $value ); $templates_dropdown .= '<option value="' . $template_value . '">' . $template_value . '</option>' . " "; } $templates_dropdown .= '</select>';
现在需要手动闭合约5个类似的select标签,想通过变量引用批量修改原变量来替代手动操作,参考示例:
$foo = 'Bob'; // 给$foo赋值'Bob' $bar = &$foo; // 通过$bar引用$foo $bar = "My name is $bar"; // 修改$bar echo $bar; echo $foo; // $foo也会被修改
问题代码
但我尝试的代码并未生效:
// 这段代码不生效 $test = 'world one'; $test2 = 'world two'; $test3 = 'world three'; $close_select_tags = array( &$test, &$test2, &$test3); foreach($close_select_tags as $value){ $value .= 'check'; } echo $test; echo " "; echo $test2; echo " "; echo $test3; echo " ";
疑问
我知道可以用数组解构或者直接把select标签变量存到数组里,但想搞明白:为什么数组里存储的变量引用修改后,原变量没有变化?
内容的提问来源于stack exchange,提问作者brittle_spirit
相关产品推荐
相关产品推荐

