dssjxvbv918586 2011-06-19 17:48
浏览 44
已采纳

PHP - 传递变量作为引用生成未指定的错误

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

tyia

  • 写回答

1条回答 默认 最新

  • donglu8549 2011-06-19 17:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?