Michael got a customer call, from a PHP system his company had put together four years ago. He pulled up the code, which thankfully was actually up to date in source control, and tried to get a grasp of what the system does.

There, he discovered a… unique way to define functions in PHP:

if(!function_exists("GetFileAsString")){
        function GetFileAsString($FileName){
                $Contents = "";
                if(file_exists($FileName)){
                        $Contents = file_get_contents($FileName);
                }
                return $Contents;
        }
}
if(!function_exists("RemoveEmptyArrayValuesAndDuplicates")){
        function RemoveEmptyArrayValuesAndDuplicates($ArrayName){
                foreach( $ArrayName as $Key => $Value ) {
                        if( empty( $ArrayName[ $Key ] ) )
                   unset( $ArrayName[ $Key ] );
                }
                $ArrayName = array_unique($ArrayName);
                $ReIndexedArray = array();
                $ReIndexedArray = array_values($ArrayName);
                return $ReIndexedArray;
        }
}

Before we talk about the function_exists nonsense, let’s comment on the functions themselves: they’re both unnecessary. file_get_contents returns a false-y value that gets converted to an empty string if you ever treat it as a string , which is exactly the same thing that GetFileAsString does. The replacement for RemoveEmptyArrayValuesAndDuplicates could also be much simpler: array_values(array_unique(array_filter($rawArray)));. That’s still complex enough it could merit its own function, but without the loop, it’s far easier to understand.

Neither of these functions needs to exist, which is why, perhaps, they’re conditional. I can only guess about how these came to be, but here’s my guess:

Once upon a time, in the Dark Times, many developers were working on the project. They worked with no best-practices, no project organization, no communication, and no thought. Each of them gradually built up a library of include files, that carried with it their own… unique solution to common problems. It became spaghetti, and then eventually a forest, and eventually, in the twisted morass of code, Sallybob’s GetFileAsString conflicted with Joebob’s GetFileAsString. The project teetered on the edge of failure… so someone tried to “fix” it, by decreeing every utility function needed this kind of guard.

I’ve seen PHP projects go down this path, though never quite to this conclusion.

[Advertisement] Application Release Automation for DevOps – integrating with best of breed development tools. Free for teams with up to 5 users. Download and learn more today!