可以在PHP中输出1行的返回值吗?

Say I have this function in PHP

<?php
function get_filename_parts($fname){
/*
receives a filename and returns an array with the filename & extension
example:
receives:   myfile1.jpg
returns:    array('filename' => 'myfile1', 'extension' => 'jpg')

receives:   myfile1.blah.blah.jpg
returns:    array('filename' => 'myfile1.blah.blah', 'extension' => 'jpg')

*/
$name_no_ext = explode('.',$fname);
$ext = array_pop($name_no_ext);
$name_no_ext = implode('.',$name_no_ext);

$retval = array('filename' => $name_no_ext, 'extension' => $ext);

return $retval;
}
?>

Is there some syntax to do something like this in a single statement:

 <?php echo get_filename_parts('test.txt')->filename; ?>

instead of:

 <?php $fname = get_filename_parts('test.txt'); echo $fname['filename']; ?>

Thanks!

In PHP 5.4, you can do the shorthand:

$fname = get_filename_parts('test.txt')['filename'];

From php version 5.4 you can use

$fname = get_filename_parts('test.txt')['filename'];

For PHP < 5.4 you can write this function:

function array_var($from, $name, $default = null) {
    if(is_array($from)) {
      return array_key_exists($name, $from) ? $from[$name] : $default;
    } 

    return $default;
} 

Then you can just write

array_var(get_filename_parts('test.txt'), 'filename');

If you are in PHP < 5.4, then you can use StdClass to mock your results:

example:

function func() {
  $results = new StdClass;

  $results->filename = 'file_name';
  $results->extension = 'extension';

  return $results;
}

echo func()->filename;

Try this:

function get_filename_parts($fname){
    $parts = explode('.', $fname);
    $obj = new StdClass;
    $obj->extension = array_pop($parts);
    $obj->filename = implode('.', $parts);
    return $obj;
}

and now you can use it the way you wanted:

<?php echo get_filename_parts('test.txt')->filename; ?>
<?php echo get_filename_parts('test.txt')->extension; ?>