1

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!

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This was a clear answer -- Bad practice, but technically valid. Also, appreciate the tip on not needing to use unset().
1

You may use var_dump() for the best practice and also you may use unset() when it remains unhelpful

Comments

1

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.

2 Comments

I appreciate the explanation. In a really large page that will get unwieldy.
I should say that the variable scope spanning 10000 lines is not just a "bigger application", it's a horrible unstructured application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.