Why does PHP not complain when I treat a null valu

2020-01-29 05:58发布

In PHP, I have error_reporting set to report everything including notices.

Why does the following not throw any notices, errors or anything else?

$myarray = null;
$myvalue = $myarray['banana'];

Troubleshooting steps:

$myarray = array();
$myvalue = $myarray['banana'];
// throws a notice, as expected ✔

$myarray = (array)null;
$myvalue = $myarray['banana'];
// throws a notice, as expected ✔

$myarray = null;
$myvalue = $myarray['banana'];
// no notice or warning thrown, $myvalue is now NULL. ✘ Why?

It's possible it's a bug in PHP, or I'm just not understanding something about how this works.

标签: php arrays null
3条回答
疯言疯语
2楼-- · 2020-01-29 06:11

There is an active bug report started at 2006.

And in documentation it is a notice about this in String section. enter image description here

查看更多
聊天终结者
3楼-- · 2020-01-29 06:19

Usually, when you try to use a value of one type as if it were another type, either an error or warning gets thrown or "type juggling" takes place. For example, if you try to concatenate two numbers with ., they'll both get coerced to strings and concatenated.

However, as explained on the manual page about type juggling, this isn't the case when treating a non-array like an array:

The behaviour of an automatic conversion to array is currently undefined.

In practice, the behaviour that happens when this "undefined behaviour" is triggered by dereferencing a non-array is that null gets returned, as you've observed. This doesn't just affect nulls - you'll also get null if you try to dereference a number or a resource.

查看更多
\"骚年 ilove
4楼-- · 2020-01-29 06:22

There are three types which it might be valid to use the array derefence syntax on:

  • Arrays
  • Strings (to access the character at the given position)
  • Object (objects implementing the ArrayAccess interface)

For all other types, PHP just returns the undefined variable.

Array dereference is handled by the FETCH_DIM_R opcode, which uses zend_fetch_dimension_address_read() to fetch the element.

As you can see, there is a special case for NULLs, and a default case, both returning the undefined variable.

查看更多
登录 后发表回答