表达式中的变量赋值如何工作

表达式中的变量赋值如何工作

本文介绍了表达式中的变量赋值如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前看过的但不是很经常的练习:一个变量被赋值给一个值,同时值本身被评估(或者它是被评估的表达式本身)。示例:

This is a practice I've seen before, but not very often: A variable is assigned to a value at the same time the value itself is evaluated (or is it the expression itself that is evaluated?). Example:

// Outputs "The value is 1"
$value = 1;
if ($var = $value) {
    echo "The value is $var";
}

似乎与以下相同:

$value = 1;
$var = $value;
if ($var) {
    echo "The value is $var";
}

另一个例子:

// Outputs "The value is 1"
$value = 1;
echo "The value is ".$var = $value;

我一直在使用这一点来缩短我的代码,主要是第一个例子:for评估第一个变量或表达式,同时将其分配给同一表达式中的另一个。如下所示:

I've been using this a little bit to shorten up my code, mainly the first example: for evaluating the first variable or expression while assigning it to another within the same expression. Something like this:

if ($status = User::save($data)) {
    echo "User saved.";
}
// do something else with $status

,但是我实际上找不到任何,也许我不知道在哪里看。我最近才明白这个工作原理,多年后,我真的很喜欢使用它,但我不想随便使用它。

This seems so basic, but I can't actually find any documentation on this, maybe I'm not sure where to look. I've only recently figured out how this works after seeing it for years, and I really like using it, but I don't want to use it haphazardly.

它使代码更短,也许不太清楚一些,但绝对少重复。这个方法有什么注意事项吗?这是完全安全的还是有可能失败或导致意想不到的行为的情况?这似乎不是一个很常见的做法,所以我希望在我开始坚持之前找到一个解释。如果 记录在案,那么将非常感谢指向正确页面的链接。

It makes code shorter, maybe not quite as clear to some, but definitely less repetitive. Are there any caveats with this method? Is this perfectly safe or are there any cases where it might fail or cause unexpected behavior? This doesn't seem to be a very common practice, so I was hoping to find an explanation before I start "going nuts" with it. If it is documented, links to the correct page will be much appreciated.

推荐答案

从:

许多人会认为你不应该经常使用这种行为。例如,区分:

Many people would argue that you shouldn't use this behaviour very often. For instance, distinguishing between:

if ($a == 5) { ... }

if ($a = 5) { ... }

很棘手!写上述两种常见的惯用方式来区别它们:

is tricky! The two common idiomatic ways of writing the above to distinguish them:

if (5 == $a) { ... }
if (($a = 5)) { ... }

第一个是称为,并导致语法错误,如果等于字符被遗漏后者在运行时不会有任何差异,但是当表达式没有额外的括号时,一些代码检查器将输出警告。

The first is called a yoda condition and causes a syntax error if a equals character is left out. The latter won't behave any differently when run, but some code checkers will output warnings when the expression doesn't have the extra parentheses.

这篇关于表达式中的变量赋值如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:55