【问题标题】:Is it possible to reference a specific element of an anonymous array in PHP?是否可以在 PHP 中引用匿名数组的特定元素?
【发布时间】:2012-01-06 18:05:50
【问题描述】:

这可能是一个简单的问题,恐怕答案可能是“不”,但是……

这是一段简单的代码:

function func1() {
  $bt = debug_backtrace();
  print "Previous function was " . $bt[1]['function'] . "\n";
}

现在...可以在没有临时变量的情况下完成吗?用另一种语言,我可能希望能够说:

function func1() {
  print "Previous function was " . (debug_backtrace())[1]['function'] . "\n";
}

唉,在 PHP 中,这会导致错误:

PHP Parse error:  syntax error, unexpected '[' ...

如果做不到就做不到,我会用一个临时变量,但我宁愿不要。

【问题讨论】:

    标签: php arrays indexing anonymous


    【解决方案1】:

    不,不幸的是,当前版本的 PHP 不支持直接取消引用,但显然会出现在 PHP 5.4 中。

    另见Terminology question on "dereferencing"?

    【讨论】:

      【解决方案2】:

      数组解引用目前在 PHP 5.3 中不可用,但它将在 PHP 5.4 (PHP 5.4.0 RC2 is currently available for you to tinker with) 中可用。同时,您可以使用end()reset() 或辅助函数来获得您想要的。

      $a = array('a','b','c');
      echo reset($a);          // echoes 'a'
      echo end($a);            // echoes 'c'
      echo dereference($a, 1); // echoes 'b'
      
      function dereference($arr, $key) {
          if(array_key_exists($key, $arr)) {
              return $array[$key];
          } else {
              trigger_error('Undefined index: '.$key); // This would be the standard
              return null;
          }
      }
      

      注意end()current() 会重置数组的内部指针,所以要小心。

      为了您的方便,如果您要链接取消引用,这可能会派上用场:

      function chained_dereference($arr, $keys) {
          foreach($keys as $key) {
              $arr = dereference($arr, $key);
          }
      
          return $arr;
      }
      
      // chained_dereference(debug_backtrace(), array(1, 'function')) = debug_backtrace()[1]['function']
      

      【讨论】:

        猜你喜欢
        • 2012-01-31
        • 2011-12-14
        • 2013-01-18
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 2011-05-29
        • 1970-01-01
        相关资源
        最近更新 更多