开发者

PHP - Passing variable as reference generated unspecified error

开发者 https://www.devze.com 2023-03-13 20:05 出处:网络
I\'m getting an error when using a variable reference.Am I missing something obvious? basically... $required = array();

I'm getting an error when using a variable reference. Am I missing something obvious?

basically...

$required = array();
$optional = array();

foreach($things as $thing){
  $list =& $thing->required ? $required : $optional;
  $list[] = $thing;
}

(looping thru list of things, if the thing's required property is true, pass that thing to the list of required things, other pass it to the list of optional things...)

开发者_JAVA百科

tyia


From the looks of it, it seems like you're trying to separate things that are required or optional into different arrays.

<?php

foreach ( $things as $thing )
{
  if ( $thing->required )
    $required[] = $thing;
  else
    $optional[] = $thing;
}

If you insist on doing it on a single line, you could do this:

<?php

foreach ( $things as $thing )
  ${$thing->required ? 'required' : 'optional'}[] = $thing;

The problem with your code is $list =& $thing->required ? $required : $optional;. PHP is ignoring the ? $required : $optional part is assigning $this->required to $list. When you try to add to the array on the following it, $list is a scalar and no longer an array so it's failing. The only way that I can think to solve that problem is to go with one of the solutions above or to create function that return the array by reference.

Reference: From http://php.net/manual/en/language.operators.comparison.php:

Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消