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:
- Use a bunch of
if/elsestatements - Use
switchstatement - Use variable functions
- Use anonymous function (define an array of anonymous functions)
- Use
call_user_funcandcall_user_func_arrayfunctions - Use polymorphism: abstract base class + a bunch of sub-classes (one per actual method)
- Use
evalstatement - Use
ReflectionMethod::invokemethod
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