Another reason why I love PHP is its ability to do so many things inline, while keeping the code flow amazingly simple. This is an inline anonymous switch statement, and it allows us to use a switch statement to return us something.
$int = 2; $value = call_user_func(function($int){ switch($int){ case 1: return 'One'; case 2: return 'Two'; case 3: return 'Three'; } }, $int); echo $value; //Output: Two
This script allows us to do an inline switch function, by using call_user_func(). And because we’re using it to return something, there’s no need for a break.
Additional tips, call_user_func is handy if your reference is dynamic and earlier unknown.
call_user_func is by design very slow, you’ll lose a lot of performance.
In modern php, you can just execute the function on the fly without call_user_func.
$value = (function($int){
switch($int){
case 1: return ‘One’;
case 2: return ‘Two’;
case 3: return ‘Three’;
}
})( $int);