First, I apologize if this just a coding style issue. I’m wondering about the pros and cons of assign a new variable for each property or function to just to re-assign an existing variable. This is assuming you don’t need access to the variable beyond the scope.
Here’s what I mean (noting that the names $var0,... are just for simplicity),
Option#1:
$var0= array('hello', 'world');
$var1="hello world";
$var2=//some crazy large database query result
$var3=//some complicated function()
vs.
Option#2:
$var0= array('hello', 'world');
$var0="hello world";
$var0=//some crazy large database query result
$var0=//some complicated function()
- Does it depend on the memory size of the existing variable? I.e., is re-assigning memory more computationally expensive that assigning a new variable?
- Is this always a scope issue, meaning you should use Option#2 only if you don’t need each of the variable values outside the scope shown here?
- Does it depend on what each variable value is? Does re-assigning to different data types have different costs associated with it?
Personally I would say you should never ever reassign a variable to contain different stuff. This makes it really hard to debug. If you are worried about memory consumption you can always
unset()variables.Also note that you should never ever have variables names
$var#. Your variablenames should describe what it holds.In the end of the day it’s all about minimizing the number of WTFs inyour code. And option two is one big WTF.
It’s about limiting the number of WTFs for both you and other people (re)viewing your code.
Well if it is in a totally other scope it is fine if you use the same name multiple names. As long as it is clear what the variabel contains, e.g.:
Not a matter of cost, but a matter of maintainability. Which is often way more important.