douwen3836 2012-03-02 21:25
浏览 34

PHP - 从返回它的方法调用数组值?

I'm trying to call an array variable directly from a method that returns it. Something like the following:

function some_meth()
{
    return array('var1' => 'var);
}

I know I can do something like this:

$var = some_meth();
$var = $var['var1'];

But I would like to be able to do this in one line, something like this:

$var = some_meth()['var1'];

This returns the error below, which makes sense, but is there a way to do this in one line?

Trying to get property of non-object
  • 写回答

2条回答 默认 最新

  • douben6670 2012-03-02 21:26
    关注

    In pre-php5.4 this is not possible in a single call. 5.4 on you can accomplish it just like in your example.

    From http://docs.php.net/manual/en/language.types.array.php

    As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

    <?php
    function getArray() {
        return array(1, 2, 3);
    }
    
    // on PHP 5.4
    $secondElement = getArray()[1];
    
    // previously
    $tmp = getArray();
    $secondElement = $tmp[1];
    
    // or
    list(, $secondElement) = getArray();
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题