PHP语法提领函数结果 [英] PHP syntax for dereferencing function result

查看:94
本文介绍了PHP语法提领函数结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

在我定期使用所有其他的编程语言,它是简单的没有宣布一个新的变量来保存函数结果一个函数的返回值进行操作。

In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring a new variable to hold the function result.

在PHP中,然而,这并不显得那么简单:

In PHP, however, this does not appear to be so simple:

<?php 
function foobar(){
    return preg_split('/\s+/', 'zero one two three four five');
}

// can php say "zero"?

/// print( foobar()[0] ); /// <-- nope
/// print( &foobar()[0] );     /// <-- nope
/// print( &foobar()->[0] );     /// <-- nope
/// print( "${foobar()}[0]" );    /// <-- nope
?>

例2(函数的结果是一个对象)

<?php    
function zoobar(){
  // NOTE: casting (object) Array() has other problems in PHP
  // see e.g., http://stackoverflow.com/questions/1869812
  $vout   = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',);
  return $vout;
}

//  can php say "zero"?       
//  print zoobar()->0;         //  <- nope (parse error)      
//  print zoobar()->{0};       //  <- nope                    
//  print zoobar()->{'0'};     //  <- nope                    
//  $vtemp = zoobar();         //  does using a variable help?
//  print $vtemp->{0};         //  <- nope     

任何人都可以建议如何在PHP中做到这一点?

Can anyone suggest how to do this in PHP?

推荐答案

这是专门数组语法,这是目前在PHP5.3不支持,但应在下一个版本,5.4是可能的。对象是提领,另一方面有可能在当前的PHP版本。我也期待着这个功能!

This is specifically array dereferencing, which is currently unsupported in php5.3 but should be possible in the next release, 5.4. Object dereferencing is on the other hand possible in current php releases. I'm also looking forward to this functionality!

这篇关于PHP语法提领函数结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆