How come a case option in a switch statement that does not contain a break automatically forwards to a next case without check?
try {
switch($param) {
In PHP 8 we have match
, similar with switch
expression but is significantly shorter:
An example:
$message = match ($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'unknown status code',
};
Here's its switch
equivalent:
switch ($statusCode) {
case 200:
case 300:
$message = null;
break;
case 400:
$message = 'not found';
break;
case 500:
$message = 'server error';
break;
default:
$message = 'unknown status code';
break;
}
reference : https://stitcher.io/blog/php-8-match-or-switch
Perhaps this will enlighten you:
Jump Table Switch Case question
I don't really see what you want.
All the tools are there.
Fallthrough was an intentional design feature for allowing code like:
switch ($command) {
case "exit":
case "quit":
quit();
break;
case "reset":
stop();
case "start":
start();
break;
}
It's designed so that execution runs down from case to case.
default
is a case like any other, except that jumping there happens if no other case was triggered. It is not by any means a "do this after running the actual selected case" instruction. In your example, you could consider:
switch($param) {
case "created":
if(!($value instanceof \DateTime))
throw new \Exception("\DateTime expected, ".gettype($value)." given for self::$param");
break;
case "Creator":
if(!($value instanceof \Base\User)) {
throw new \Exception(get_class($value)." given. \Base\User expected for self::\$Creator");
}
break;
}
$this->$param = $value;
The rule of thumb here is, if it doesn't depend on the switch, move it out of the switch.
Because that's how it's done in C.
To answer your "actual question": Why does it continue with the "Creator" case while the case is not "Creator".
Because you do not have break
. Without it, it will continue to the cases below it. The only solution I can think of is putting your default code to the cases, and add break
.
Also, you don't need break
on the default case since its the last case in the switch block.