通过引用和三元运算符分配变量? [英] Assigning variables by reference and ternary operator?

查看:139
本文介绍了通过引用和三元运算符分配变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么三元运算符不能通过引用进行分配?

Why ternary operator doesn't work with assignment by reference?

$obj     = new stdClass(); // Object to add
$result  = true; // Op result
$success = array(); // Destination array for success
$errors  = array(); // Destination array for errors

// Working
$target = &$success;
if(!$result) $target = &errors;
array_push($target, $obj);

// Not working
$target = $result ? &$success : &$errors;
array_push($target, $obj);


推荐答案

在这里

$target = ($result ? &$success : &$errors);

您的示例也有两个错字

http://php.net /manual/zh-CN/language.operators.comparison.php


注意:请注意,三元运算符是一个表达式,但它没有不是对变量求值,而是对表达式的结果求值。了解是否要通过引用返回变量很重要。语句返回$ var == 42? $ a:$ b;因此,按引用返回功能中的命令将不起作用,并且在更高版本的PHP中会发出警告。

Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

idk如果以前曾起作用,但它不能不再了。如果您不想使用if语句,请尝试以下操作:

idk if this worked before, but it doesn't anymore. if you don't wanna use an if statement, then try this:

$result ? $target = &$success : $target = &$errors;

或在单独的行上...

or on separated lines ...

$result 
  ? $target = &$success 
  : $target = &$errors;

这篇关于通过引用和三元运算符分配变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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