Search code examples
phpphp-7code-structurecode-standards

What are the advantages of function calls without mixed variables?


I know PHP is a very error tolerant language and I guess that is why you can have mixed variables for function calls like:

/**
 * @param mixed $bar
 **/
function foo($bar) {
    // Do something with $bar, but check it's type!
}

Is there a recommended way of NOT using such mixed variables?

For my own projects, I try to avoid such mixed variables, just to have less problems with errors later and for code clarity.

And with PHP 7, it should be possible to declare what type of variable this function is expecting, shouldn't it? How is this done?


Solution

  • This will likely get closed as being "based on opinion", but it's still a good question.

    A function should do one thing. If you need to do this:

    if it's a string
        do this
    else if it's a Foo object
        do this other thing
    

    Then it's doing more than one thing, which is "less than ideal" form.

    Why don't you just provide two well-named methods instead, eg: getThingById(int) and getThingByFilters(Filters) or getThingLike(string) etc? It'll make your code more readable and predictable, too.