开发者

Assign changed variable to the same variable is safe?

Is this good practice and is there开发者_C百科 any chance of fubar if i assign slightly changed value of variable to itself?

e.g.

$myVar = 1;
$myVar = $myVar + 33959902;
$myVar = rtrim($myVar,2);
$myVar  = explode(",",$myVar);

i know this will work but is this safe to do so in PHP?


This violates the practice of using good variable names -- if the variable truly represents the same thing then I would consider re-assigning to it. As it does not represent the same thing in this case, I consider it "bad" or "code smell".

(It will, however, "work safely" otherwise.)

Happy coding.


Yes.

Not always the best for readability/maintainability. But it's safe since PHP is a dynamic and weak typed language.


It's perfectly fine to do so. Some people combine them all into one line but I sort of like this method.

I disagree with the other answers though. Personally, I think assigning different variables to each step is more confusing. Seeing that each variable is the same tells me that this block of statements all relate to each other. Makes it look more like a math problem as you're solving it step by step. I would say that this does follow the practice of assigning good variable names. It's just a different style of the method.


PHP is a weakly/loosely typed language, meaning you don't need to declare the type of a variable before assigning a value to it and you can switch the data type of a variable whenever you want.

So you can do so, but I wouldn't recommend to switch data types of a variable on the run, because this may lead to serious maintenance problems. To me, it's a bad practice.

Personally I usually even use some kind of hungarian notation (like $iCount, $oObject, etc.) for variable identifiers to make the code easier to read and maintain for others.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜