Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

Why does PHP not complain when I treat a null value as an array like this?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...