Re:Modern PHP features explained – PHP 8.0 and 8.1
by ryangittins on Thursday October 27, 2022 @01:01PM
(#33360599)
I've seen the same hack done with `switch (true)` in pre-PHP8 code (and other languages) as well.
Re:Modern PHP features explained – PHP 8.0 and 8.1
by gremlinsinc on Thursday October 27, 2022 @07:10PM
(#33365266)
match is basically a cleaner, more succinct switch, I hardly ever used switches before, though I use match a LOT.
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
verses: $output = match($i) {
0 => 'i equals 0',
1 => 'i equals 1',
2 => 'i equals 2',
default => 'i is unknown'
}
echo $output;
the result is basically the same, but match is more of an enclosed switch that just returns instead of does side effects, then you can do what you like w/ that.Ymmv, but match is a great code saver, and is very nice for enums and methods on enums.
Before match i'd probably do something like:
$output = 'i is unknown';
if($i == 0){
return 'i equals 0';
}
if($i == 1) {
return 'i equals 1';
}
if ($i == 2) {
return 'i equals 2';
}
return $output;
Not really, I'd probably do.. if($i) {
return "i equals {$i}";
}
return 'i is unknown';
but the point was if I had to check for multiples to match something, then do something else, that's how I would do it... albeit this is a simple case with a better solution.
Re:Modern PHP features explained – PHP 8.0 and 8.1
by jw1224 on Thursday October 27, 2022 @01:34PM
(#33361060)
I use `match` like this a lot now, often with PHP 8.1's enums[1]. It makes it easy to write clean dynamic accessors, without all the extra blocks required with multiple `if` branches:
/** Check the status of this Task instance. */
public function status(): Status
{
return match (true) {
$this->inProgress() || $this->isInReview() => Status::Started,
$this->isApproved() || $this->isRejected() => Status::Finished,
default => Status::Planned,
};
}
[1] https://stitcher.io/blog/php-enums
Re:Modern PHP features explained – PHP 8.0 and 8.1
by randomguy0 on Thursday October 27, 2022 @01:59PM
(#33361422)
What am I missing? Isn’t that the output that makes sense? Or am I misunderstanding your comment about it being hacky?
Re:Modern PHP features explained – PHP 8.0 and 8.1
by generallee5686 on Thursday October 27, 2022 @02:01PM
(#33361460)
I think they're talking about the "match (true)".
https://www.php.net/manual/en/control-structures.match.php#e...
The above example will output: