This question is mainly opinionated, but you managed to raise a valid question.
Just for quick reference, in PHP 7 there is the null coalesce operator that does this quickly and effective in 1 short code:
$id = $id ?? -1;
or chained $id = $id ?? $this->id ?? -1
As this compares every ?? {arg} ?? {arg}
with isset()
But why don't do it with an or statement?
Pros
- It's short (1-lining)
- Fairly fast and easy to read.
- Less complex than ternary operators
- Most likely faster in code-parsing
Cons
- I'ts very deceiving
If you do not fully understand how type comparisons work in PHP, it will eventually bite you. If you thought of this like isset()
you are dead wrong and would read the code incorrectly because of it it. For this reason I would vote against using this method.
expression if isset empty
$x = ""; FALSE TRUE TRUE
$x = null; FALSE FALSE TRUE
var $x; FALSE FALSE TRUE
$x (undefined) FALSE FALSE TRUE
$x = []; FALSE TRUE TRUE
$x = ['a', 'b']; TRUE TRUE FALSE
$x = false; FALSE TRUE TRUE
$x = true; TRUE TRUE FALSE
$x = 1; TRUE TRUE FALSE
$x = 42; TRUE TRUE FALSE
$x = 0; FALSE TRUE TRUE
$x = -1; TRUE TRUE FALSE
$x = "1"; TRUE TRUE FALSE
$x = "0"; FALSE TRUE TRUE
$x = "-1"; TRUE TRUE FALSE
$x = "php"; TRUE TRUE FALSE
$x = "true"; TRUE TRUE FALSE
$x = "false"; TRUE TRUE FALSE
For a full list of the table you can see this link.
It works like !empty()
, see the following example:
if(($id or $id = $this->id) > 0){
echo "Greater then 0";
}
if(($id = !empty($id) ? $id : $this->id) > 0){
echo "Greater then 0";
}
Most people are not aware of this. The code isn't obvious to read as well. So while I am perfectly able to read the code now, It will be a bit more confusing when I read over it next month.
There is also a question in this code if $this->id
is actually set, could create bugs in code.