我正在尝试修复我的旧网站,该网站目前无法正常运行。我已将问题简化为以下代码:
<?php
global $options;
foreach ( $options as $value ) {
if ( isset( $value['id'] ) ) {
var_dump($value);
$test = $value['id'];
if ( get_option( $value['id'] ) === FALSE ) {
$$value['id'] = $value['std'];
} else {
$$value['id'] = get_option( $value['id'] );
}
var_dump($$value['id']); // returns "Boxed"
var_dump($$test); // return NULL
break;
}
}
?>
$ value变量的var_dump为:
array(6) { ["name"]=> string(10) "Theme Type" ["desc"]=> string(29) "Select the type of the theme." ["id"]=> string(10) "celta_type" ["type"]=> string(6) "select" ["options"]=> array(2) { [0]=> string(5) "Boxed" [1]=> string(9) "Stretched" } ["std"]=> string(5) "Boxed" } string(5) "Boxed" NULL array(6) { ["name"]=> string(10) "Theme Type" ["desc"]=> string(29) "Select the type of the theme." ["id"]=> string(10) "celta_type" ["type"]=> string(6) "select" ["options"]=> array(2) { [0]=> string(5) "Boxed" [1]=> string(9) "Stretched" }
我不理解以下内容:输出$$ value ['id']如何工作,但是首先将值赋给$ test = $ value ['id'],结果为$$ test不工作。
旧网站使用的是非常旧的PHP版本(<5.3),在新的PHP版本中是否发生了某些变化?
感谢在正确方向上的点
您需要将$$value['id']
替换为${$value['id']}
。
这是因为:
$cheese['id']
,即,您正在使用键$cheese
寻找一个名为id
的数组['id' => 'celta_type']
,则动态变量将解析为$celta_type
这被称为歧义问题,请参见此处:https://www.php.net/manual/en/language.variables.variable.php
您是正确的,这在PHP 5和PHP 7之间发生了变化:https://www.php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect
顺便说一句,如果我是您,我不会使用动态变量,因为它们不安全且不可预测。您可以重写函数以使用数组,如下所示:
$optionValues[$value['id']] = get_option($value['id']);
if ($optionValues[$value['id']] === false)
$optionValues[$value['id']] = $value['std'];
或
$optionValues[$value['id']] = get_option($value['id']) === false ? $value['std'] : get_option($value['id']);