Does it matter if I use 1 php variable several times for different purposes?

I use the variables $ query, $ row, etc. in my code several times and assign them different things. I wonder if this matters or the wrong coding style? Does this affect website or server performance?

+4
source share
4 answers

Assigning different values ​​to variables is accurate. These are what variables are for, in fact. This becomes a problem if you assign variables to variables. For example, reusing a variable called $query to store something that is not a query can be confusing and unintuitive for anyone who needs to maintain code (including you after you forget about it).

As long as the variables retain what they mean in the context of the code, you can reassign them to whatever you want.

+8
source

It depends, and there is no single answer, you know.

In cases where you specify ($ query, $ row), it is better to use variabls.

So, just make it reasonable and don't make yourself a problem out of nowhere.

+2
source

it doesn’t matter, since php is not a strongly typed language, but freely typed . This means that your variable dynamically changes it in accordance with what you put into it.

However, it is not a good coding practice to simply use a single variable to insert something, since the variables should be called descriptive. So you want to use $ row to store a row, not a column (to make an example).

+1
source

In general, reusing the same variable can be confusing, depending on how your code is structured. But this should not be the final type of rule. Representation of a group of variables with names like query1, query2, etc. Could be even worse.

One thing I propose to do is refactor your code so that the common parts are inside a function or method. Thus, the scope of the variable will be limited by this function or method.

+1
source

Source: https://habr.com/ru/post/1369507/


All Articles