1 minute read
A quick look at the PHP match expression
If you still reach for switch, this post by Ashley Allen is a nice refresher on why match can be cleaner.
Key bits I liked:
- match uses strict comparison (===), so types must match.
- You can stack multiple cases in one arm.
- match(true) lets you write simple rule checks.
- It pairs well with enums and can be exhaustive without a default.
A tiny taste:
return match ($driver) { 'github', 'self-hosted' => new GitHubDriver(), 'gitlab' => new GitLabDriver(), 'bitbucket' => new BitbucketDriver(), default => throw new InvalidArgumentException(), };
I found the enum example especially useful for turning stored values into friendly labels. If you are on PHP 8.0 or higher, this is an easy win for tidy code.
Read more on ashallendesign.co.uk →
Did you like this article? Then, keep learning:
- Review PHP 8.4 features for staying informed about PHP's evolving capabilities
- Learn tips on fixing PHP warnings including constructor method changes
- Understand PHP 8.3's Override attribute, enhancing code clarity like match does
- See new features in PHP 8.3 to stay updated alongside match expression
- Learn about PHP 9.0 and planned breaking changes for future-proof coding
- Dive deeper into PHP array manipulation functions to enhance your coding skills
- Explore PHP enums for safer, cleaner code—complements match expression usage
- Discover error handling in PHP with try & catch for cleaner code flow
- Master printing and debugging arrays in PHP and Laravel, aiding code insight
- Discover practical PHP serialization techniques essential for handling complex data
0 comments