vendredi 2 janvier 2015

What are best practices to call different methods based on a variable value in PHP?


Vote count:

0




What are best practices to call different methods based on some variable value in PHP? Like this:



if ($var == 'someValue1') {
$someObj->abc();
} elseif ($var == 'someValue2') {
$someObj->def();
} elseif ...
} elseif ($var == 'someValueN') {
$someObj->xyz();
}


It seems that there are many ways to accomplish this task. At least, I've found the following options:



  1. Use a bunch of if/else statements

  2. Use switch statement

  3. Use variable functions

  4. Use anonymous function (define an array of anonymous functions)

  5. Use call_user_func and call_user_func_array functions

  6. Use polymorphism: abstract base class + a bunch of sub-classes (one per actual method)

  7. Use eval statement

  8. Use ReflectionMethod::invoke method


Maybe, there are some other ways which I haven't found yet.


So, which ways are better and which should be avoided (for situations with 3, 5, 7 and 10+ possible cases)? It is interesting from the following perspectives: speed, readability, maintainability, security, portability (supported by most servers and hosting providers) and understandability for most developers.



asked 1 min ago







What are best practices to call different methods based on a variable value in PHP?

Aucun commentaire:

Enregistrer un commentaire