相关疑难解决方法(0)

用于解除引用函数结果的PHP语法

背景

在我定期使用的每种其他编程语言中,操作函数的返回值很简单,而不会声明一个新变量来保存函数结果.

但是,在PHP中,这看起来并不那么简单:

example1(函数结果是一个数组)

<?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
?>
Run Code Online (Sandbox Code Playgroud)

example2(函数结果是一个对象)

<?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"? …
Run Code Online (Sandbox Code Playgroud)

php arrays syntax function

34
推荐指数
8
解决办法
2万
查看次数

标签 统计

arrays ×1

function ×1

php ×1

syntax ×1