php-src icon indicating copy to clipboard operation
php-src copied to clipboard

Silencing the non-existence of a local variable

Open dg opened this issue 4 years ago • 2 comments

Description

I'm not quite sure where to open this topic? Is it better to post it here or in php.internals or elsewhere?

PHP has made incredible progress in the last two major versions in the strictness of error conditions. Deprecating dynamic properties in PHP 8.2 is the next big step in this area. But I see two things here that are unnecessarily loose and cover errors arising from oversight or typos. It would be great if their behavior could be changed in PHP 9.

In practice, the absence of a local variable is almost always a logical error. But the isset construct and the ?? operator hide them. These examples produces no warning:

// $arr doesn't exist
$foo = isset($arr[1]);
$foo = $arr[1] ?? null;

Both constructs are used primarily to see if the array contains the element. And if the $arr variable doesn't exist, it's usually because of a bug in the code that I'd like to be informed about. So I would expect a warning Undefined variable $arr.

On the other hand, and maybe unexpectedly, the unset draws attention to this:

// $arr doesn't exist
unset($arr[1]); // Warning: Undefined variable $arr

It would be great if isset and ?? behaved the same as unset.

The same applies to objects and properties, ie. $obj->foo. Paradoxically, in this case, unset is also silent missing variable since PHP 7.4. PHP has taken a step backwards in this area. https://3v4l.org/BaRNF

In the case of objects, there is also ?-> operator that already behaves correctly:

// $obj doesn't exist
$obj?->foo; // Warning: Undefined variable $obj

What do you think about this?

dg avatar Feb 05 '22 01:02 dg

This isn't the best place for a discussion. If you'd like to pursue this then check out the RFC process. https://wiki.php.net/rfc/howto

damianwadley avatar Feb 05 '22 02:02 damianwadley

I'm creating the "Requires RFC" status for reports like this as it's not fair to call them "invalid". (Would also make more sense this way if they were to be reopened later. Plus searchability and other nice things that come with more accurate classifications.)

damianwadley avatar Feb 05 '22 02:02 damianwadley