PHP syntax for dereferencing function result

2018-12-31 04:45发布

Background

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.

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

example1 (function result is an array)

<?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
?>

example2 (function result is an object)

<?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     

Can anyone suggest how to do this in PHP?

22条回答
弹指情弦暗扣
2楼-- · 2018-12-31 05:02

After further research I believe the answer is no, a temporary variable like that is indeed the canonical way to deal with an array returned from a function.

Looks like this will change starting in PHP 5.4.

Also, this answer was originally for this version of the question:

How to avoid temporary variables in PHP when using an array returned from a function

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 05:03

If you just want to return the first item in the array, use the current() function.

return current($foo->getBarArray());

http://php.net/manual/en/function.current.php

查看更多
谁念西风独自凉
4楼-- · 2018-12-31 05:03

You could, of course, return an object instead of an array and access it this way:

echo "This should be 2: " . test()->b ."\n";

But I didn't find a possibility to do this with an array :(

查看更多
牵手、夕阳
5楼-- · 2018-12-31 05:04

Does this work?

 return ($foo->getBarArray())[0];

Otherwise, can you post the getBarArray() function? I don't see why that wouldn't work from what you posted so far.

查看更多
何处买醉
6楼-- · 2018-12-31 05:06

There isn't a way to do that unfortunately, although it is in most other programming languages.

If you really wanted to do a one liner, you could make a function called a() and do something like

$test = a(func(), 1); // second parameter is the key.

But other than that, func()[1] is not supported in PHP.

查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 05:06

Write a wrapper function that will accomplish the same. Because of PHP's easy type-casting this can be pretty open-ended:

function array_value ($array, $key) {
return $array[$key];
}
查看更多
登录 后发表回答