Hello,

I would like to suggest a new PHP operator, which in my opinion PHP needs to become more stricter. At first, I invited nullish coalescing (??) operator, since it made my code shorter and easier to read. However, after some time, I realized that this is not a good way to go, since it makes my code much less strict. The nullish coalescing function is what I need, however what I don't
want in some cases is its error suppression function.

Here is an example I use a lot while generating forms:
<input value="<?=$var->prop1->prop2 ?? ''?>" />

I have ?? operator here, mainly because prop2 can be undefined, but in a lot of cases I know that prop1 exists, or at least $var. Issue is, that there is no error outputted even when $var is undefined and I missed such errors a lot. In my opinion is not good to learn people to suppress
whatever error might occur in the whole expression.

Back to the suggestion - I suggest creating a new IFNULL operator, which will simply test if expression is null. If not, it returns left-hand part, if yes, it returns right-hand part. A suggested token for such operator is "??:" as a mix between "??" and "?:" tokens. Basically elvis token "?:" but with strict comparison to null, instead of loose comparison to false.

With new suggested operator a safe way to write expression above, where I only expect prop2 to
be undefined would look like this:

$var->prop1?->prop2 ??: '';

Notice, that use of newer operator "?->" really fits here. It clearly marks, what I expect to be undefined and "??:" operator just takes the role of converting possible "null" into and
empty string.

What do you think about this? Is it worth to introduce this new operator to promote more strictness of PHP? Is it worth to create an RFC for this? I never did an RFC yet and has not much experience with C++, since I am mostly Delphi/PHP/JS developer, but I might try. Still, I would
appreciate a help from someone willing and experienced in RFC creation.

Thank you in advance for your opinions,
David Kolář

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to