I am often in a situation when the variable can be object
or null
.
When I put data into the database I have to stick with something like this:
// @var User|null $user
$data['id_user'] = $user!==null ? $user->getId() : null;
Is there any way to shorthen this? I am aware of ??
, but this is somewhat opposite.
I am using PHP 7.1.
As of PHP 8, there is the nullsafe operator ?->
. With it you could refactor your code like this:
// @var User|null $user
$data['id_user'] = $user?->getId();
Prior to PHP 8, you could utilize automatic bool converting to take advantage of the fact that, when converting to bool, null is considered false, but other objects are not (except apparently SimpleXML objects created from empty tags are also considered false). So you could shorten your example to the following:
// @var User|null $user
$data['id_user'] = $user ? $user->getId() : null;
However, this might be less readable since the ? might imply to some people you are working with a bool to begin with, or it could make the reader have to think about how null gets converted to bool. Your original code is more explicit, and thus potentially more readable. In order to make brains work less hard, I often at least consider avoiding using "not equals" whenever possible, and just go with a straight "equals". So you could refactor your code to be like this:
// @var User|null $user
$data['id_user'] = $user === null ? null : $user->getId();
In this particular case, I think that trick (avoiding "not equals") works fairly well, but sometimes counterintuitively, the code is still more naturally readable to just use a "not equals" anyways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With