You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:50:20