Skip to content

Instantly share code, notes, and snippets.

@ircmaxell
Last active July 6, 2017 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ircmaxell/205bb6cb00d9a4cf8035 to your computer and use it in GitHub Desktop.
Save ircmaxell/205bb6cb00d9a4cf8035 to your computer and use it in GitHub Desktop.
<?php
function fibo(int $n): int {
return match($n) {
case 1: 1;
case 0: 1;
case _<0: throw new Exception("Less than 0 is not allowed, " . _ . " provided");
case _: fibo(_ - 1) + fibo(_ - 2);
};
}
<?php
$people = [
["name" => "foo", "age" => 25],
new User("bar", 33),
["user" => new User("baz", 31)],
];
function getAge($user) {
return match($user) {
case ["age" => _]: _;
case User: $user->getAge();
case ["user" => _]: _->getAge();
}
}
getAge($people[0]); // 25
getAge($people[1]); // 33
getAge($people[2]); // 31
@rijnhard
Copy link

I mentioned $_ because then you could reuse the existing functionality to embed the place holders into double quoted strings.

which IMHO is very useful for conciseness.

@ircmaxell
Copy link
Author

Sure, I was just demonstrating the concept. The exact syntax is definitely up for grabs.

@rijnhard
Copy link

Honestly I really didnt think it would look that good in php. Looks a bit better then scala even.

@cereal-s
Copy link

cereal-s commented Jul 6, 2017

Hi,

I was looking at your examples, which PHP version are you using? I cannot find any documentation about the match() statement, not even in the RFCs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment