![]() ![]() Note that since there is no default, a non-match (in this case if $count is 0 or negative) will result in a thrown error rather than silently assigning to null and moving on. If you need more complex conditions than simple identity, you can use match on true: 0 & $count 'small', match, in contrast, works for any number of options but has the same incentives to nudge you toward well-factored, clean code. That only works for true/ false, however. I've found that to be a really good heuristic for situations like this, as well as leading to very readable, compact, and testable code. If the logic in the condition or in either of the branches is too complex to be easily readable, that's a hint the logic should be refactored out to its own function or method. That's completely valid code and quite useful. The easiest way to write that, I've found, is like this: isAdmin() In the past, I've often found myself in binary cases where a variable can be assigned to one of two values depending on some condition. Rather, I think of match as a more powerful ternary. Match was pitched as a modernized, more useful switch, but I am not sure that's accurate. Match branches can also be compound and comma-delimited for "OR" like behavior, like so: 'Basic arithmetic', If $var is not = any of the provided values and there is no default, an error will be thrown. Because it's an expression, a closing is needed at the very end, just like with closure definitions.There is no fall through from one branch to the next, so there's no need for a break.If you need complex logic, make it a function or method that you call. No multi-line statements, just a single expression that gets evaluated. Each branch of the match is a single expression only.With match, each branch is compared with strict equality, =. With switch, each case is compared with loose equality =.There are several things to point out here: You've surely seen it before: 'The variable was a',ĭefault => 'The variable was something else', PHP has had a switch statement since the dawn of time, modeled on the same construct in C. Today we look at a new construct that makes branching logic more powerful. In our last episode, we discussed coming improvements to PHP's type system. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |