Assigning variables by reference and ternary operator?

不打扰是莪最后的温柔 提交于 2019-12-19 07:11:45

问题


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

回答1:


Here you go

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

Also your example has two typos


edit

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 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

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;


来源:https://stackoverflow.com/questions/8551905/assigning-variables-by-reference-and-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!