将更改的变量分配给同一个变量安全吗?
这是一个好的做法吗?如果我将稍微改变的变量值分配给自身,是否有可能出现 fubar?
例如,
$myVar = 1;
$myVar = $myVar + 33959902;
$myVar = rtrim($myVar,2);
$myVar = explode(",",$myVar);
我知道这会起作用,但是在 PHP 中这样做安全吗?
Is this good practice and is there 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这违反了使用良好变量名称的做法——如果变量确实代表相同的事物,那么我会考虑重新分配给它。由于在本例中它不代表相同的事物,因此我认为它“不好”或“代码味道”。
(但是,否则它会“安全地工作”。)
快乐的编码。
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.
是的。
并不总是最好的可读性/可维护性。但它是安全的,因为 PHP 是一种动态弱类型语言。
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 是一种弱/松散类型语言,这意味着在为变量赋值之前不需要声明变量的类型,并且可以随时切换变量的数据类型。
所以你可以这样做,但我不建议在运行时切换变量的数据类型,因为这可能会导致严重的维护问题。对我来说,这是一个不好的做法。
就我个人而言,我什至通常使用某种匈牙利表示法(例如 $iCount、$oObject 等)变量标识符以使代码更易于其他人阅读和维护。
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.