On Sun, Feb 27, 2022 at 12:10 AM Mark Randall <marand...@php.net> wrote:

> On 26/02/2022 22:34, Robert Landers wrote:
> > This is not semantically the same though. A $_POST of a form, for
> example,
> > will usually contain an empty value if the form input was empty, but
> > missing if the form control wasn't in the form (maybe the form control is
> > injected via Javascript, or conditionally output by the script).
>
>
> PHP is a general purpose language, the behaviour you're asking for is
> specific to one use case and may be of detriment to others, without
> offering significant benefit in exchange.


> I suggest you write yourself a function that performs the operations for
> you. This may also be a good opportunity to move away from directly
> accessing the superglobals in userland code.
>
> $form->get('foo', 'defaultgoeshere');
>

I gave that as an example, not a literal line from real code, just to show
how common the situation is. Handling data structures like YAML, JSON, or
parsing virtually any file format will run into this issue where you want
to set a default if the value is falsy or non-existent. I've written a lot
of this parsing-type of code over the years and run into this case at least
once each time.

> PHP is a general purpose language, the behaviour you're asking for is
> specific to one use case and may be of detriment to others, without
> offering significant benefit in exchange.

I'd also venture that this warning has caused more harm than good, in that
writing "$var['something'] ?? null" is second nature when writing new
code, even if there is practically no chance for a non-existent key. This
requires reviewers and authors to go digging into the source of the array
and trace it to its usage, just to figure out whether or not a key can be
non-existent under certain conditions (or discover a warning in
production). In my experience, arrays are usually derived from user/machine
input, which is impossible to predict the exact shape (outdated clients,
malicious users, etc.) and the warning becomes noise with enough traffic.

 Perhaps a non-existent key should result in null by default (without a
warning, but maybe a notice) unless you want a different value (using "??")?


>
> Performance concerns would be so so small they would be practically
> undetectable in the context of a real request.


> Also, this:
>
> $name = empty($_POST['name'] ?? 'Default Name') ?: 'Default Name';
>
> Should be:
>
> $name = ($_POST['name'] ?? null) ?: 'Default Name')
>
> --
> Mark Randall
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Reply via email to