更快 $foo 吗? $foo : “酒吧”
一行代码讲了无数个单词,所以:
$foo = false;
$bar = $foo ? $foo : 'bar';
/* $bar == 'bar' */
$foo = 'foo';
$bar = $foo ? $foo : 'bar';
/* $bar == 'foo' */
有没有一种更快的方式来表达“如果某件事不是假的,那么就不要改变它(如果 $foo
不是 false< /code> 然后它保持原样,否则,我们将更改它)”?
A line of code speaks a gazillion words so:
$foo = false;
$bar = $foo ? $foo : 'bar';
/* $bar == 'bar' */
$foo = 'foo';
$bar = $foo ? $foo : 'bar';
/* $bar == 'foo' */
Is there a quicker way of saying "if something isn't false, then don't change it (if $foo
isn't false
then it stays as whatever it was, else, we'll change it)"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
真的:那真的很短! :D 然而,从 5.3 开始它变得更短
Really: Thats really short! :D However, since 5.3 it gets even shorter
不仅要考虑更快的写作,还要考虑更快的阅读。
最终你会发现舒适的阅读比这些愚蠢的写作技巧更重要。
Try to think not only of quicker writing but also of quicker reading.
Eventually you will learn that comfortable reading is way more important than these silly tricks in writing.
应该返回 'bar
应该返回 true;
5.3 的AS
should return 'bar
should return true;
AS of 5.3
用什么标准来衡量“更快”?
就运行时而言,这永远不会成为您的瓶颈,所以不必担心。
就易读性而言,以下内容显然更容易阅读:
"Quicker" by what metric?
In terms of runtime, this will never be your bottleneck, so don't worry about it.
In terms of legibility, the following is clearly easier to read:
我担心的是你可能有一个转换为 false 的值
你不会通过直接的、类型敏感的比较得到这个值
My concern is that you could have a value that casts to false
You wont get that with a direct, type sensitive comparison
不知道为什么总是被忘记,但还有一种 Perl 式的语法:
或者在你的情况下只是:
我经常使用过多的空格来保持可读性。最重要的是,除非 $foo 为 false,否则它实际上不会进行任何赋值。
Not sure why that's always forgotten, but there is also a Perl-esque syntax:
Or in your case just:
I'm often using excessive spaces to keep it readable. Most importantly it really does no assignment unless $foo is false.