这里不是错误抑制的忠实拥护者,除非是丢弃的脚本或确实没有很好的方法来捕获错误的实例。
让我解释一下Uninitialized string offset
错误的行为。这不是一个错误:
示例 #1
$a = 0;
$b = $a['f5'];
$a
是数值标量值。在第二行中,PHP 隐式将此数值转换为字符串。该字符串'0'
的长度为 1。
在 PHP 中,您可以使用数组索引在字符串中查找字符,因为 PHP 在内部将字符串存储为数组。例如:
$s= 'abcd';
print_r($s[1]);
此代码的输出将是b
字符串中的第二个字符。在示例 #1 中,查找'f5'
被转换为数字,因为字符串只能按字符位置索引。echo intval('f5');
向我们展示了 PHP在数字上下文中将'f5'
字符串解释为什么。0
跟我到现在?当我们将其应用于示例 #2 时会发生以下情况
示例 #2
$a = '';
$b = $a['f5'];
$a
is zero-length string. The second line is the same as $b= $a[0];
- i.e., the second line is asking for the first character of a zero-length string, but the string contains no characters. So PHP throws the following error, letting you know the index simply does not exist:
Notice: Uninitialized string offset: 0 in C:\websites\tcv3\wc2009\htdocs\aatest_array.php on line 3
These are the hard knocks of programming in a loosely typed language.