Switch-Based Activity Types0:00
Next up, we have match expressions. I'm really excited about this one. So I've set up an example for something like an activity feed. Let's say various models can generate activity in the database. Likely as part of that, you'll need a string that represents the activity type. So here we have a switch class that inspects the class, whether it's a Comment or a Conversation or a Reply or something else. And it says, well, if that class is Conversation, then the activity type is startedConversation. If it's a Reply, then it's repliedToConversation. If it's a Comment, you get the idea.
Introducing Match Expressions0:32
If it's a reply, then it's repliedToConversation. If it's a comment, you get the idea. And sure enough, if I were to echo out the type and give it a run, we get startedConversation because our object is a Conversation. However, if we were to rewrite this with php 8 match expressions, it gets much cleaner. And actually, little tip, in PHPStorm, you can do that automatically. But for this first iteration, I want to do it manually with you. We'll use this new match keyword. Match the name of the class. Now within here, this is very much like key value pairs.
Writing the Match Mapping1:02
Match the name of the class. Now within here, this is very much like key value pairs. If it's conversation, we're not using a colon, stick with the arrow, then we have startedConversation. Next, if it's reply, then it's repliedToConversation. And then lastly, if it's comment, then it's commentedOnLesson. So again, notice how it's effectively key value pairs. Let's go ahead and save the type from that match call. Give it a run, and we get the exact same thing. But notice how much cleaner this is. We only have to assign the type variable once, since the matching value is returned from
Benefits and IDE Conversion1:35
But notice how much cleaner this is. We only have to assign the type variable once, since the matching value is returned from match. And then of course, we don't need the break keywords as well. So yet again, it works in PHP 8, but in PHP 7, of course it's going to fail. And that's really it. So last little thing, like I mentioned in PHPStorm, if I option return, I can automatically convert my switch statements. So much better.
