PHP Bad Practice: Variable Reuse
Join the DZone community and get the full member experience.
Join For FreeAnyone who has worked with PHP knows that it is extremely permissive with variables and their types. There's no need to declare variables, not even at class level, and data types cannot really be enforced. This is one of the greatest strengths of weakly typed dynamic languages, but it can be easily used the wrong way.
The problem
Variable reuse is one such unfortunate case, which can easily lead to unmaintainable code.
Let me illustrate by this example:
$fruit = array(1 => “orange”, 2 => “banana”);
// Some code using the $item array
$fruit = $fruit[2];
As you can see, the $fruit
variable starts out as an
associative array and is used as such to perform various tasks. After a
while, it gets reassigned and points to a string typed value inside the
array.
Now what if you need some other items from your fruit array in some newly added code? You will not be able to do that, since the array is no longer available. This is especially troublesome if the functionality is added by someone else. That developer will need to figure out what is going on, modify the existing code and only afterward implement the new feature.
During our various migration projects, I have regularly encountered
code that uses this annoying pattern. Such constructs are not yet
explicitly handled by our type inference algorithm and so we end up
with Java variables of java.lang.Object
type. This is obviously not a nice thing in the generated code.
Not even larger PHP code base is free from variable reuse. From the open-source world, phpBB and WordPress come to my mind as heavy users of this construct.
The solution
Variables should be named consistently, based on the data they hold. While regarding variable types and their declarations the opinions are diverging (see static vs. dynamic typing), the meaning of the variable content is fundamental and should be reflected by its naming.
With this in mind, the above code should rather look like this:
$fruits = array(1 => “orange”, 2 => “banana”);
// Some code using the $item array
$favourite_fruit = $fruits[2];
Now isn't this much cleaner and maintainable? Had I written this, it would make me sleep better at night :-)
Published at DZone with permission of Robert Enyedi, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Does the OCP Exam Still Make Sense?
-
RBAC With API Gateway and Open Policy Agent (OPA)
-
Multi-Stream Joins With SQL
-
Developers Are Scaling Faster Than Ever: Here’s How Security Can Keep Up
Comments