奇怪的变量赋值 [英] Strange variable assignment

查看:25
本文介绍了奇怪的变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在研究我在网上找到的一些代码,并遇到了这个 php 语法:

<?php $framecharset &&$frame['charset'] = $framecharset;?>

有人能解释一下这行代码是怎么回事吗?什么变量被分配什么值,&&&&&&&&&&&&&&&运算符,在语句的那个​​位置?

谢谢!拍

解决方案

啊,我刚刚在 javascript 中写了一篇关于这个习语的博文:

http://www.mcphersonindustries.com/

基本上是在测试 $framecharset 是否存在,然后尝试将其分配给 $frame['charset'] 如果它不为空.>

它的工作方式是解释器是懒惰的.&& 语句的两边都需要为真才能继续.当它遇到 false 值后跟 && 时,它会停止.它不会继续评估(因此在这种情况下,如果 $framecharsetfalsenull,则不会发生分配).

有些人甚至会在 && 之后放置布尔表达式的更昂贵"的一半,这样如果第一个条件不是 true,那么昂贵的位将永远不会被处理.这实际上可以节省多少是有争议的,但它使用相同的原则.

I was studying some code I found on the web recently, and came across this php syntax:

<?php $framecharset && $frame['charset'] = $framecharset; ?>

Can someone explain what is going on in this line of code? What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?

Thanks! Pat

解决方案

Ah, I just wrote a blog post about this idiom in javascript:

http://www.mcphersonindustries.com/

Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.

The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).

Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.

这篇关于奇怪的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆