Reusing Variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Reusing Variables

Post by JakeJ »

In my application, I reuse a lot of my variables. In particular I reuse $txt a lot because it seems to me, that it's a lot easier to reuse it than it would be to create an insane amount of variables.

What I don't know is, is it more efficient in the application/memory sense to reuse the same variable or or declare one for each text string I need to use? Maybe to put it more simply, where is there more overhead, overwriting a variable or instantiating a new one?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Reusing Variables

Post by Benjamin »

This is actually the least of your worries. DB queries, classes, included files and memory usage impact performance an order of magnitudes more than variable usage.
marty pain
Forum Contributor
Posts: 105
Joined: Thu Jun 11, 2009 5:32 am
Location: Essex

Re: Reusing Variables

Post by marty pain »

You get less overhead by re-using variables, but it is minimal so do what ever is easier for you and other people to understand.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Reusing Variables

Post by JakeJ »

In this case, reusing the variable is the easiest and most readable since it's getting stuck inside a function anyway. I suspected it was also the best utilization of memory, etc. also but things are not always as they appear so I thought I'd check but I really wasn't willing to take the time to do benchmarking to figure it out.
siji86
Forum Commoner
Posts: 30
Joined: Fri Mar 26, 2010 6:15 am

Re: Reusing Variables

Post by siji86 »

Reusing the variable is perfectly ok, but it makes the code difficult to understand for example, if i have used customer_id somewhere and later on i use customer_id to store a email id then this seems a bit confusing. So according to me its better to reuse variables only when neccessary.
JakeJ
Forum Regular
Posts: 675
Joined: Thu Dec 10, 2009 6:27 pm

Re: Reusing Variables

Post by JakeJ »

In this case, I'm just reusing a variable called $txt which as you might guess is text. Not likely to cause confusion in this case but I take your point.
Post Reply