2

I have this code on PHP 7.2.x:

class Test
{
    public $prop = null;
}
$temp = new Test();
var_dump($temp->prop['fff']);

but why is not reported Warning when temp->prop['fff'] not exists?

Edit1: sorry I forget add this code here:

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1); //all errors
step
  • 2,254
  • 2
  • 23
  • 45

2 Answers2

4

I found something in the documentation:

Note:

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

So it seems to be by design, although it's not clear why. Personally I would at least expect an E_NOTICE.

There is a link to a bug report in the comments of that page, which in turn is marked as duplicate of another bug. This one seems to be neither fixed nor closed. So maybe it will be changed/fixed in the future.

Community
  • 1
  • 1
Karsten Koop
  • 2,475
  • 1
  • 18
  • 23
0

It is interesting observation,(all comments are wrong,too)

error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
class Test
{
    public $prop = null;
}
$temp = new Test();

var_dump($temp->prop);

$variable = null;
var_dump($variable['test']);

the code above will not render issues either, even when forcing error reporting. My guess is the non-existing key warning is only meant for arrays, and not nulls. Truth is, I cannot fin WHY exactly this is nor reported, but then again I cannot find any real reason why anyone would do this kind of implementation (and maybe that's the reason the warning is not shown). When you need the particular element to require a specific key, your best shot is implementing a ValueObject design pattern and not array with a key.

Jan Myszkier
  • 2,714
  • 1
  • 16
  • 23