Q:

How to execute a function decided by incoming parameter without if else

$arg = $_POST['argument'];
class a{
    public function sayYes(){
       echo 'Yes';
    }
    public function sayNo(){
       echo 'No';
    }
}

Here how do i execute sayYes if arg is 'yes' or execute sayNo if arg is 'no' without using if else asking it because if i had 30 functions it wouldn't be efficient

A:

For the sake of syntax sugar, here are two ways in the spirit you are asking for.

Using an object

$arg = 'yes';

class a {
    public static function sayYes() {
       echo 'Yes';
    }
    public static function sayNo() {
       echo 'No';
    }
}

a::{'say'.ucfirst($arg)}();

Using an array

$arg = 'yes';

$funcs = [
    'yes' => function () {
        echo 'Yes';
    },
    'no' => function () {
        echo 'No';
    }
];

$funcs[$arg]();

Note: tested with PHP 7.2

