Thursday, August 25, 2011

Explicit is better than implicit

Explicit is better than implicit is one of python's Zen. Coming to PHP, however, there are too many ways to make things implicitly. One of them is variable variable:


$var = 'name';
$$var = 'henry';
echo $name;

The output is 'henry'. Maybe this code snippet is not that horrible. But sometimes it is not that simple.

There was once I tried to locate where a variable is defined. The variable is $branchName, for example. It is being used directly in a file in this way: echo $branchName; and it works, so the variable must be defined/assigned a value somewhere else. Since the legacy code is procedure style, so I naturally trace back to other files that are included into the file. It must be one of those included files in which $branchName is defined. However, I can't find it. So i start to search the whole application, but i still can't find any place that defines $branchName.

The first possibility i can come up with is, register global, another notorious php feature. The application is so old that register global is turned on and used. Unfortunately, I still can't find any place showing that $branchName is a register global.

Then, i think that must be a variable variable, so i search the string '$$' in those included files. I cannot find any. I start to get a little confused. But suddenly, i remember that PHP can define variable variable in two ways: $$var = 'henry' or ${$var} = 'henry'. They both work. So i try to search '${$' in the files, finally, i found this code, with a comment from a prior developer, which is funny:


for ($i = 0, $last = count($parameters); $i < $last; $i++) {
        //Good ol' dollar-dollar string interpolation... um, yeah, "thanks".
    ${$parameters[$i]['name']} = $parameters[$i]['value'];
}

When i var_dump($parameters), I finally found this 'branchName'. PHP can make things so implicitly, and even worse, it provides different ways to do implicit thing while Python preaches there should be only one way to do the same thing. That is why when i learned the fact that "Ruby inherited the Perl philosophy of having more than one way to do the same thing", I immediately dump this language into my rubbish bin and never want to touch it again, unless i was forced to.

No comments: