php中赋值表达式的值,php – 表达式中的变量赋值如何工作?

这是我之前见过的一种做法,但不常见:在评估值本身的同时将一个变量赋值给一个值(或者它是被评估的表达式本身?).例:

// 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;

我一直在使用它来缩短我的代码,主要是第一个例子:用于评估第一个变量或表达式,同时将它分配给同一个表达式中的另一个.像这样的东西:

if ($status = User::save($data)) {

echo "User saved.";

}

// do something else with $status

这看起来很基本,但我实际上找不到任何documentation,也许我不知道在哪里看.我最近才知道它在看了多年之后是如何工作的,我真的很喜欢使用它,但我不想随意使用它.

它使代码更短,可能对某些人来说不太清楚,但肯定不那么重复.这种方法有什么警告吗?这是完全安全还是有任何可能导致失败或导致意外行为的情况?这似乎不是一种非常普遍的做法,所以我希望在开始“疯狂”之前找到解释.如果有文档记录,将非常感谢指向正确页面的链接.

解决方法:

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we’ve already dealt with, $a = 5. It’s easy to see that there are two values involved here, the value of the integer constant 5, and the value of $a which is being updated to 5 as well. But the truth is that there’s one additional value involved here, and that’s the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that $a = 5, regardless of what it does, is an expression with the value 5. Thus, writing something like $b = ($a = 5) is like writing $a = 5; $b = 5; (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write $b = $a = 5.

很多人会争辩说你不应该经常使用这种行为.例如,区分:

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

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

很棘手!以上两种常用的惯用方式来区分它们:

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

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

第一个称为yoda condition,如果省略了等号,则会导致语法错误.后者在运行时不会有任何不同的行为,但是当表达式没有额外的括号时,一些代码检查器会输出警告.

标签:php,variables,expression,variable-assignment

来源: https://codeday.me/bug/20190730/1576996.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值