PHP 的可变变量是否有使解决方案更清晰的情况?
可能的重复:
变量变量的实际用途是什么?
是否存在以下情况: PHP的可变变量使解决方案更清晰?
例如这个:
$a = 'hello';
$$a = 'hello, world!';
echo $hello;
Possible Duplicate:
what's an actual use of variable variables?
Is there any case in which PHP's variable variables make a solution clearer?
E.g. this:
$a = 'hello';
$a = 'hello, world!';
echo $hello;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的示例并不完全是针对变量变量,但其意图相似,因为为了清楚起见,它涉及从包含类实例的变量中访问类常量。
当您不使用命名空间时,最终类名会变得相当长。这周我正在编写一些代码,需要执行一些 switch 语句来确定要从遗留系统的结果中写回的消息,但我不想直接比较结果代码,因此我将代码作为常量班级。
想象一下还有七个案例。
类名太长了,当我把它作为一个案例时,它看起来又大又丑又难以阅读。
因此,为了让自己轻松起来,我将一个新类保存到一个变量中,并引用其中的常量。
这里的变量简化了代码,使其更加清晰。
我本可以更接近你的例子:
但我不想让下一个不得不重命名我的常量的可怜灵魂的生活变得困难!
因此,虽然不完全相同,但这为您提供了可变变量的一些可能用途的现实生活示例。
(但就我个人而言,我会说,避开!)
My example is not exactly over variable variables, but it is similar in intent, as it involves accessing class constants out of a variable containing an instance of the class for the purpose of clarity.
When you are not using namespacing, eventually class names get to be pretty long. I was writing some code this week that needed to do some switch statements to determine the message to write back from a result from a legacy system, but I did not want to compare the result code directly, so I put the code as a constant on the class.
Imagine this with seven more cases.
The class name is so long, when I went to put it as a case, it looked huge, ugly and hard to read.
So, to make it easy on myself, I saved a new class into a variable, and referenced the constants from that.
The variable here neatens the code to make it far more legible.
I could have taken it a step closer to your example with:
But I did not want to make life difficult for the next poor soul who had to rename my constant!
So, while not exactly the same thing, this gives you a real life example of a few possible uses for variable variables.
(But personally, I would say, steer clear!)