PHP: Inline Switch Statement (Anonymous Function)

Published on Author Yani2 Comments

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.

 

 

Categories PHP

2 Responses to PHP: Inline Switch Statement (Anonymous Function)

  1. 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);

Leave a Reply

Your email address will not be published. Required fields are marked *