How does the “Array dereferencing” work on a scalar value of type boolean/integer/float/string as of PHP version 7.2.0?

坚强是说给别人听的谎言 提交于 2019-11-30 20:44:09

问题


I am using PHP 7.2. I come across the following note from the arrays chapter of PHP Manual

Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.

I understand how to dereference an array literal but I'm not able to understand how the "array dereferencing" works on a scalar value of type boolean/integer/float/string?

If you look at the code example from the PHP manual itself, you can notice the contradiction as it's not the value of integer type is not silently yielding NULL according to the manual.

<?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

How is dereferencing a scalar value of type boolean/integer/float different from dereferencing the value of type string?


回答1:


They are referring to non-complex types such as int or float.

In your example you are using an array. So you don't see the issue.

<?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);

The first pair of brackets is array-dereferencing on the array (1, 2222, 3), the second is array-dereferencing on an integer (2222) which always returns null.

Simplified:

<?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

This "fails silently" as in theory you should get an error from this, rather than just null.

Also happens with null, other than int, float, bool:

<?php 
$a = true;
var_dump($a[42][42][42][42][42][42][42][42]); // also null, and no errors

But works correctly instead with arrays and strings.

<?php
$a = "abc";
var_dump($a[1]); // b
$a = [11, 22, 33];
var_dump($a[1]); // 22

Answering your question, "How does the “Array dereferencing” work on a scalar value of type": It doesn't, it just returns null instead of returning an error of some sort.



来源:https://stackoverflow.com/questions/48032002/how-does-the-array-dereferencing-work-on-a-scalar-value-of-type-boolean-intege

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!