Switch expression for PHP
Plugin for the XP Compiler which adds switch expressions to the PHP language.
Example
use util\Date;
use lang\IllegalArgumentException;
public function serialize($arg) {
return switch ($arg) {
case true => 'b:1;';
case false => 'b:0;';
case null => 'N;';
case is int => 'i:'.$arg.';';
case is string => 's:'.strlen($arg).'"'.$arg.'";';
case is Date => '@:'.$arg->getTime().';';
default => throw new IllegalArgumentException('Unhandled '.typeof($arg));
};
}
Installation
After installing the XP Compiler into your project, also include this plugin.
$ composer require xp-framework/compiler
# ...
$ composer require xp-lang/php-switch-expression
# ...
No further action is required.
See also
- https://wiki.php.net/rfc/switch-expression-and-statement-improvement
- https://blog.codefx.org/java/switch-expressions/
- https://kotlinlang.org/docs/reference/control-flow.html#when-expression
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/patterns#switch-expression