Closed thekid closed 5 years ago
Alternative suggestion for type matching, which would go along the is
infix operator as suggested in #68:
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));
};
}
See https://kotlinlang.org/docs/reference/control-flow.html#when-expression
Can be implemented as external plugin once #66 is merged - see https://github.com/xp-lang/php-switch-expression
Introduces
=> expr
as (kind of) shorthand for: return expr
like with short lambdas and compact functions, and makesswitch
an expression. The type tests borrow from the casting syntax.Example
See https://blog.codefx.org/java/switch-expressions/