Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$foo["bar"] = 1; Can I ask PHP to complain if $foo doesn't exist?

Tags:

php

Take this line of PHP:

$foo["bar"] = 1;

I would like PHP to throw an exception if $foo doesn't exist. Right now, it doesn't throw an exception, or even print an error or warning even with display_errors set to 1 and error_reporting called with E_ALL. Instead, it creates an array $foo and sets $foo["bar"] to 1, even though the variable $foo did not exist beforehand.

Is there something like declare(strict_types=1); that will enable checking this?

The reason I want this is so that I can more easily detect typos when I accidentally misspell a variable name.

like image 881
Flimm Avatar asked Jan 24 '26 15:01

Flimm


1 Answers

Unfortunately, you are setting up an array with the command. Why would php throw an exception if you are setting up this?

It's like assigning a value to a variable and then asking why did PHP assign the value to the variable?

$foo["bar"] = 1;

print_r($foo);
// This prints the following: 
// Array ( [bar] => 1 )

The correct way of checking would be:

if(isset($foo))
{
  $foo['bar'] = 1;
}
else
{
  // do something if $foo does not exist or is null
}

Hope this helps! In short the answer to your question is no: there isn't a way to make PHP throw an exception or print a warning in your example.

like image 108
veggito Avatar answered Jan 27 '26 04:01

veggito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!