Switch case final in PHP or why goto bad.
-
Problem
There's a challenge to use.
switch
differentcase
Do the codedefault
(orfinal
To be implemented, so as not to duplicate the same code in different cases.switch ("b") { case 'a': case 'z': case 'q': echo "a\n"; // not need run default action break; case 'b': echo "b\n"; // need run default case without case 'c' break; case 'c': echo "c\n"; default: echo "default"; // need run for "b" & "c" cases }
Turns out:
b
I would like to:
b default
If you take it away.
break
variantb
the extra code will be completedb c default
There's a solution.
goto
which is a bad coding style:switch ("b") { case 'a': echo "a\n"; break; case 'b': echo "b\n"; goto caseFinal; break; case 'c': echo "c\n"; goto caseFinal; break; default: caseFinal: echo "default"; }
Full mission
There's a range of fields of different nature and different fields have to do.
switch ($fieldName) { case 'id': // не нужно default unset($properties['actions']['create']); unset($properties['actions']['edit']); break; case 'content': // одинаковый код нужно вынести в defaut unset($properties['actions']['dashboard']); // ... break; case 'isDeleted': // одинаковый код нужно вынести в defaut unset($properties['actions']['dashboard']); // ... break; default: // код нужне для всех остальных полей + кейсы выше unset($properties['actions']['dashboard']); }
Question
How to do this without using
goto
? Maybe there's a way in the architecture.P.S. If
goto
It's appropriate. http://php.net/manual/ru/control-structures.goto.php Why is this bad coding style?
-
Why make it harder? It is possible to reproduce the code into the class function/method and to call it from each case. The code will be as good as it is.
goto
We don't use and the code remains readable and easily supported:function someAction() { //some code }
switch ($fieldName) {
case 'id':
unset($properties['actions']['create']);
unset($properties['actions']['edit']);
break;
case 'content':
someAction();
unset($properties['actions']['dashboard']);
// ...
break;
case 'isDeleted':
someAction();
unset($properties['actions']['dashboard']);
// ...
break;
default:
someAction();
unset($properties['actions']['dashboard']);
}