Reputation: 1205
Basic PHP Question...
Is it okay to use the same variable name ($image) over and over again in the same php file, if you keep changing it's value? Or do you need to do $image1, $image2 and so on...?
It's working to do it with the same variable/different values, but I'm not sure if it's a bad practice? (I'm still learning, obviously.)
Here's a simplified example:
$image = get_field('image_3');
echo $image
...
$image = get_field('image_5');
echo $image
Also, I'm referring to what I assume are global variables. The variable is not set within an individual function. Do I need to unset the variable each time if I do it this way? Or is this ok?
Thanks!
Upvotes: 1
Views: 119
Reputation: 5133
As PHP is not a typed language, you may do this.
Typed (Java):
float i = 3.563
string s = "3.563"
Non-Typed (PHP):
e.g on Line 10: i = 3.563;
Then, further down: i = "3.563";
In a non-typed programming language, it is up to you, to not having a chaos with your var-names. My advice is:
Basically, it is allowed, but...
If suddenly, you'll put a boolean or a float in previously stringed variable, I'd say, that's not clean programming.
You may encounter problems in bigger applications. Here's why:
For you as a programmer, it's cleaner to create another variable for other values, than e.g.
$image = get_field('image_3');
and further down you say: $image = true;
Will you remember on line 10'000 (or as commented: on line 42) what kind of value you had in the $image
var?
But if you have an $image
var and a $someThingIstrue
var, you'll see by the name of the variable, what it's for.
Upvotes: 1
Reputation: 10121
You may use var_dump()
for the best practice and also you may use unset()
when it remains unhelpful
Upvotes: 1
Reputation: 2228
Of course it's a bad practice, because it's hard to understand what is it currently inside the $image
when reading the source code.
However, it's perfectly valid PHP code, variables in imperative languages like the Algol family of languages are meant to be changed.
By the way, you almost never need to unset()
the value of a variable, only in clever tricks or when working with really large datasets.
Upvotes: 1