在 PHP return NULL 中访问布尔变量作为数组
Accessing boolean var as array in PHP return NULL
与我工作的朋友讨论,我们发现了一些关于 PHP 的奇怪之处。让我们得到以下代码:
<?php
$leo = false;
$retorno = $leo[0];
var_dump($retorno);
var_dump()
的return是NULL
。现在,问题是,为什么 returning NULL,如果我们试图访问 bool
作为 array
?
正确的行为不是抛出异常告诉我们,我们正在尝试将非数组对象作为数组访问(在本例中为布尔变量)?
你们怎么看?
因为您尝试访问的不是字符串,而是布尔值 returns NULL
。从 manual:
Note:
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.
它是 NULL
,因为 $leo[0]
不是 $leo
。您尚未将 bool
或 string
分配给 $leo[0]
,因此它是空的,最终结果是 NULL
.
如果你要输入:
$retorno = $leo;
或者
$leo[0] = false;
那么你会得到你期望的结果。
$leo = false;
$retorno = array($leo);
var_dump($retorno[0]);
试试这个
与我工作的朋友讨论,我们发现了一些关于 PHP 的奇怪之处。让我们得到以下代码:
<?php
$leo = false;
$retorno = $leo[0];
var_dump($retorno);
var_dump()
的return是NULL
。现在,问题是,为什么 returning NULL,如果我们试图访问 bool
作为 array
?
正确的行为不是抛出异常告诉我们,我们正在尝试将非数组对象作为数组访问(在本例中为布尔变量)?
你们怎么看?
因为您尝试访问的不是字符串,而是布尔值 returns NULL
。从 manual:
Note: Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.
它是 NULL
,因为 $leo[0]
不是 $leo
。您尚未将 bool
或 string
分配给 $leo[0]
,因此它是空的,最终结果是 NULL
.
如果你要输入:
$retorno = $leo;
或者
$leo[0] = false;
那么你会得到你期望的结果。
$leo = false;
$retorno = array($leo);
var_dump($retorno[0]);
试试这个