1 php arrays scalar null dereference
我使用的是PHP 7.2.我从PHP手册的数组章节中看到了以下注释
取消引用不是字符串的标量值的数组静默产生NULL,即不发出错误消息.
我理解如何取消引用数组文字,但我无法理解"数组解除引用"如何在boolean/integer/float/string类型的标量值上工作?
如果你看一下PHP手册本身的代码示例,你可以注意到矛盾,因为根据手册,整数类型的值不是默默地产生NULL.
<?php
function getArray() {
return array(1, 2, 3);
}
$secondElement = getArray()[1];
var_dump($secondElement); // int(2)
//According to the manual I expected it to be NULL as it's not of type string
Run Code Online (Sandbox Code Playgroud)
如何取消引用boolean/integer/float类型的标量值与取消引用string类型的值不同?
它们指的是非复杂类型,如int或float.
在您的示例中,您使用的是数组.所以你没有看到这个问题.
<?php
function getArray() {
return array(1, 2222, 3);
}
$secondElement = getArray()[1]; // 2222
$null = $secondElement[123456]; // 123456 can be any number or string
var_dump($null);
// similarly:
$also_null = getArray()[1][45678];
var_dump($also_null);
Run Code Online (Sandbox Code Playgroud)
第一对括号是数组上的数组解除引用(1,2222,3),第二对是整数(2222)上的数组解除引用,它总是返回null.
简化:
<?php
$a = 123456;
var_dump($a[42]); // is null
$a = 123.45;
var_dump($a[42]); // is null
$a = true;
var_dump($a[42]); // is null
$a = null;
var_dump($a[42]); // is null
Run Code Online (Sandbox Code Playgroud)
这个"无声地失败",因为理论上你应该从中得到一个错误,而不仅仅是null.
除了int,float,bool之外,还会出现null:
<?php
$a = true;
var_dump($a[42][42][42][42][42][42][42][42]); // also null, and no errors
Run Code Online (Sandbox Code Playgroud)
但是使用数组和字符串正确工作.
<?php
$a = "abc";
var_dump($a[1]); // b
$a = [11, 22, 33];
var_dump($a[1]); // 22
Run Code Online (Sandbox Code Playgroud)
回答你的问题,"如何做的'数组语法’ 工作的类型的标值":它不,它只是返回null而不是返回某种类型的错误.
| 归档时间: |
|
| 查看次数: |
244 次 |
| 最近记录: |