|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2008-02-29 23:41 UTC] php at dafydd dot com
Description:
------------
In writing with PHP, I have frequently come across situations where I would have to nest switch() functions. So, I thought of an alternative.
Reproduce code:
---------------
Current code:
Suppose I have one variable limited to four specific values, and a second variable that identifies whether or not the first variable can be changed. Right now, I have to do this:
switch ($value) {
case 'a':
switch ($access) {
case 'read-only':
case 'read-write':
}
case 'b':
switch ($access) {
case 'read-only':
case 'read-write':
}
case 'c':
switch ($access) {
case 'read-only':
case 'read-write':
}
case 'd':
switch ($access) {
case 'read-only':
case 'read-write':
}
}
Expected result:
----------------
Instead of doing that, how about changing switch to track multiple variables. Perhaps like this:
switch ($value, $access) {
case ('a', 'read-only'):
case ('a', 'read-write'):
case ('a', default):
case ('b', 'read-only'):
case ('b', 'read-write'):
case ('b', default):
case ('c', 'read-only'):
case ('c', 'read-write'):
case ('c', default):
case ('d', 'read-only'):
case ('d', 'read-write'):
case ('d', default):
case (default, default):
}
This would reduce repetition in coding!
Actual result:
--------------
I fully anticipate that this would be an "incorporate into PHP 7" class of new feature.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 01 17:00:02 2025 UTC |
Hi, this is actually possible already in PHP already, and doesn't need any extra functionality. You can specify a function to be called to combine multiple arguments into a single value inside case statements like this: function f($value, $access = null) { $knownAccessTypes = [ 'read-only', 'read-write' ]; if (in_array($access, $knownAccessTypes)) { return $value.$access; } return $value; } function multiSwitchFunction($value, $access = null) { switch (f($value, $access)) { case f('a', 'read-only'): return 'a r'; case f('a', 'read-write'): return 'a w'; case f('a'): return 'a default'; case f('b', 'read-only'): return 'b r'; case f('b', 'read-write'): return 'b w '; case f('c', 'read-only'): return 'c r'; case f('c', 'read-write'): return 'c w'; case f('d', 'read-only'): return 'd r'; case f('d', 'read-write'): return 'd w' ; default: return "unknown"; } } var_dump(multiSwitchFunction('a', 'read-write')); var_dump(multiSwitchFunction('a', 'foobar')); var_dump(multiSwitchFunction('d', 'read-write')); var_dump(multiSwitchFunction('d', 'foobar')); If that doesn't suite your needs, it might be better to discuss the exact feature you would like on the PHP internals list, where an RFC could be discussed.