Match
caution
Match expression is natively supported since PHP 8 version. We recommend using that instead of the munus match. Munus match is a great option for PHP 7 support.
Match is an expression similar to the switch statement. It has a subject expression that is compared against multiple alternatives. All of the alternatives return value, which is the result of expression if the alternative is matched.
Construction#
To use match, you need to specify some alternatives. Each match expression can include multiple normal cases and one default case.
- PHP 7
- PHP 8
There are four types of cases in munus:
caseOf($value, $other)- it's the case that compare value, and returns other value if is matchedcaseCall($value, callable $callable)- it's the case that compare value, and returns the result of executed callabledefaultOf($other)- it's the default case that is matched if any of others are not, and returns other valuedefaultCall(callable $callable)- it's the default case that is matched if any of others are not, and returns the result of executed callable
Callable#
Both munus and native match allow using callables as results.
- PHP 7
- PHP 8
There is a small difference between them. In the native match, you can put the expression that in the normal way, should be run, but in the match, it will be executed only if the alternative is matched. You can get the same behavior in munus match. It's not the most beautiful solution, but it works the same.
- PHP 7
- PHP 8
Exception#
A match statement requires to match at least one of the alternatives, if there is no match, it throws an exception.
- PHP 7
- PHP 8
Predicates#
Munus provides some predicates, that helps with building alternatives.
isIn(iterable $values)- acceptsiterableof any type, and check if value is matched to any of themisInstanceOf(string $className)- accepts the class name, and check if the value is the instance of itisNull()- check if the value is nullisNotNull()- check if the value is not nullisValue($value)- accepts value of any type and check if the values are sameisAllOf(Predicate ...$predicates)- acceptsiterableof predicates, and check if all of them are matchedisAnyOf(Predicate ...$predicates)- acceptsiterableof predicates, and check if any of them is matchedisNoneOf(Predicate ...$predicates)- acceptsiterableof predicates, and check if none of them are matched
Usage#
In PHP 8 where the match is natively supported, you can also use predicates in expressions. Every predicate is the implementation of the Munus\Match\Predicate interface. This interface has meet($value): bool method, which executes the predicate, and returns bool value.
It's not always more readable solution, but you can choose which you want.
IsIn#
- PHP 7
- PHP 8
- PHP 8 (predicates)
IsInstanceOf#
- PHP 7
- PHP 8
- PHP 8 (predicates)
IsAllOf#
- PHP 7
- PHP 8
- PHP 8 (predicates)
IsAnyOf#
- PHP 7
- PHP 8
- PHP 8 (predicates)
IsNoneOf#
- PHP 7
- PHP 8
- PHP 8 (predicates)