简体   繁体   English

通过引用和三元运算符分配变量?

[英]Assigning variables by reference and ternary operator?

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

Here you go 干得好

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

Also your example has two typos 你的例子也有两个拼写错误


edit 编辑

http://php.net/manual/en/language.operators.comparison.php http://php.net/manual/en/language.operators.comparison.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 ? 声明返回$ var == 42? $a : $b; $ a:$ b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions. 因此,在返回引用函数中将不起作用,并且在以后的PHP版本中发出警告。

idk if this worked before, but it doesn't anymore. idk如果之前有效,但它不再存在了。 if you don't wanna use an if statement, then try this: 如果你不想使用if语句,那么试试这个:

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

or on separated lines ... 或分开的线......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM