Re: [RFC] anti-coalescing-operator
| From: | Ken Stanley | Date: | Thu, 24 Oct 2019 18:59:12 +0000 |
| Subject: | Re: [RFC] anti-coalescing-operator | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-107665@lists.php.net to get a copy of this message | ||
On Thu, Oct 24, 2019 at 1:33 PM Dan Ackroyd <Danack@basereality.com> wrote:
> On Thu, 24 Oct 2019 at 18:21, Ken Stanley <dohpaz@gmail.com> wrote:
> >
> > Since PHP 7.0 brought forward the Null Coalescing Operator (??), writing
> > more succinct code for how to handle null values has been a blessing.
> But,
> > what about the inverse when you want to do something when a value is not
> > null?
>
> Hi Ken,
>
> It may help to give a real world example, rather than a metasyntactic
> one, as I can't immediately see how this would be useful.
>
> People have been expressing a concern over 'symbol soup' for similar
> ideas. The null colalesce scenario happens frequently enough, that it
> seemed to overcome the hurdle needed for acceptance. Again, giving a
> real world example of what you currently need to do frequently might
> help other people understand the need.
>
> cheers
> Dan
>
Hi Dan,
After some thought, and searching through my existing code bases, I believe
I've come up with a decent code example to help demonstrate the usefulness
of the proposed anti-coalescing-operator:
Without !??:
<?php
class ExampleController
{
/**
* PATCH a User object.
*/
public function saveAction(int $userId)
{
$user = $this->getUser($userId);
if (isset($_SERVER['fname']) {
$user->setName($_SERVER['fname']);
}
if (isset($_SERVER['lname']) {
$user->setName($_SERVER['lname']);
}
if (isset($_SERVER['mname']) {
$user->setName($_SERVER['mname']);
}
if (isset($_SERVER['phone']) {
$user->setName($_SERVER['phone']);
}
if (isset($_SERVER['email']) {
$user->setName($_SERVER['email']);
}
$this-saveUser($user);
}
}
With !??:
<?php
class ExampleController
{
/**
* PATCH a User object.
*/
public function saveAction(int $userId)
{
$user = $this->getUser($userId);
$_SERVER['fname'] !?? $user->setName($_SERVER['fname']);
$_SERVER['lname'] !?? $user->setName($_SERVER['lname']);
$_SERVER['mname'] !?? $user->setName($_SERVER['mname']);
$_SERVER['phone'] !?? $user->setName($_SERVER['phone']);
$_SERVER['email'] !?? $user->setName($_SERVER['email']);
$this-saveUser($user);
}
}
Thank you,
Ken Stanley