开发者

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

开发者 https://www.devze.com 2023-04-01 01:25 出处:网络
I\'m using $qu开发者_C百科ery, $row, etc.. variables in my code multiple time, and assigning different things to them. I wonder if it\'s matter or wrong coding style? Does it affect to website or serv

I'm using $qu开发者_C百科ery, $row, etc.. variables in my code multiple time, and assigning different things to them. I wonder if it's matter or wrong coding style? Does it affect to website or server performance anyway?


Assigning different values to variables is fine. It's what variables are for, really. It only becomes a problem if you assign different meanings to the variables. For example, re-using a variable called $query to hold something that isn't a query can be confusing and unintuitive to anybody who has to support the code (including yourself after you've forgotten about it).

As long as the variables maintain what they mean in the context of the code, you can re-assign them all you want.


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

In cases you mention ($query, $row) it's better to reuse variabls.

So, just make it sensible and don't make yourself a trouble out of nowhere.


it doesn't matter, as php is not a strictly typed language, but a loosely typed one. That means, that your variable dynamically changes it's type according to what you put in it.

However, it's not good coding practice to simply use one variable to put in anything, as variables are supposed to be name descriptive. So you want to use $row to store a row and not a column (to make an example).


In general, reusing the same variable may lead to confusion, depending on how your code is structured. But this should not be a end-all be-all type of rule. Introducing a bunch of variables with names like query1, query2, etc. can be even worse.

One thing I would suggest doing is refactoring your code so that the common parts are inside a function or method, that way, that variable's scope will be limited to that function or method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号