Pattern matching in Phunkie provides a functional way to destructure and match on complex data types, working alongside PHP’s native pattern matching features.
Phunkie’s pattern matching combines with PHP’s match
expression:
$on = pmatch($value);
$result = match(true) {
$on(42) => "Found 42",
$on(_) => "Something else"
};
// PHP native match
$status = match($value) {
200 => "OK",
404 => "Not Found",
default => "Unknown"
};
// Phunkie pattern matching
$on = pmatch(Some($response));
$status = match(true) {
$on(Just($code)) => match($code) {
200 => "OK",
404 => "Not Found",
default => "Unknown"
},
$on(None()) => "No Response"
};
enum Status {
case Success;
case Error;
}
$on = pmatch(Some(Status::Success));
$result = match(true) {
$on(Just(Status::Success)) => "All good!",
$on(Just(Status::Error)) => "Something went wrong",
$on(None()) => "No status"
};
use function Phunkie\PatternMatching\Referenced\Some as Just;
$on = pmatch(Some(42));
$result = match(true) {
$on(Just($x)) => "Got $x",
$on(None()) => "Got nothing"
}; // "Got 42"
use function Phunkie\PatternMatching\Referenced\ListWithTail;
$on = pmatch(ImmList(1, 2, 3));
$result = match(true) {
$on(Nil()) => "Empty list",
$on(ListWithTail($head, $tail)) => "First: $head",
}; // "First: 1"
use function Phunkie\PatternMatching\Referenced\Success as Valid;
use function Phunkie\PatternMatching\Referenced\Failure as Invalid;
$on = pmatch(Success("yay!"));
$result = match(true) {
$on(Valid($x)) => "Success: $x",
$on(Invalid($e)) => "Failed: $e"
}; // "Success: yay!"
Combine patterns with conditions:
$on = pmatch(Some(42));
$result = match(true) {
$on(Just($x)) && $x > 50 => "Large number",
$on(Just($x)) => "Number: $x",
$on(None()) => "No number"
}; // "Number: 42"
The underscore (_
) matches any value:
$on = pmatch(ImmList(1, 2, 3));
$result = match(true) {
$on(ListWithTail($first, _)) => "First is $first",
$on(_) => "Something else"
}; // "First is 1"
match
for simple value matchingmatch
expression