您正在尝试访问string,就像它是一个数组一样,其键是string。 string 不会理解。在代码中我们可以看到问题:
"hello"["hello"];
// PHP Warning: Illegal string offset 'hello' in php shell code on line 1
"hello"[0];
// No errors.
array("hello" => "val")["hello"];
// No errors. This is *probably* what you wanted.
深入
让我们看看那个错误:
警告:非法字符串偏移 'port' in ...
它说什么?它说我们正在尝试使用字符串'port' 作为字符串的偏移量。像这样:
$a_string = "string";
// This is ok:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...
// !! Not good:
echo $a_string['port'];
// !! Warning: Illegal string offset 'port' in ...
是什么原因造成的?
由于某种原因,您期望的是array,但您却拥有string。只是混搭。也许你的变量被改变了,也许它从来都不是array,这真的不重要。
可以做什么?
如果我们知道我们应该有一个array,我们应该做一些基本的调试来确定为什么我们没有一个array。如果我们不知道是array 还是string,事情就会变得有点棘手。
我们可以做的是各种检查,以确保我们没有通知、警告或错误,例如 is_array 和 isset 或 array_key_exists:
$a_string = "string";
$an_array = array('port' => 'the_port');
if (is_array($a_string) && isset($a_string['port'])) {
// No problem, we'll never get here.
echo $a_string['port'];
}
if (is_array($an_array) && isset($an_array['port'])) {
// Ok!
echo $an_array['port']; // the_port
}
if (is_array($an_array) && isset($an_array['unset_key'])) {
// No problem again, we won't enter.
echo $an_array['unset_key'];
}
// Similar, but with array_key_exists
if (is_array($an_array) && array_key_exists('port', $an_array)) {
// Ok!
echo $an_array['port']; // the_port
}
isset 和 array_key_exists 之间存在一些细微差别。例如,如果$array['key'] 的值为null,则isset 返回false。 array_key_exists 只会检查密钥是否存在。