在PHP中,在调用函数中返回多个数据的最佳方式是什么


What is the optimum way to return more than one data in a call function in PHP?

我有两个函数调用,调用者调用历史xch函数

private function historicalxch($arg){
   ...
     $data['MaxLow'] = max($data['ArrayLow']);
     $data['MinLow'] = min($data['ArrayLow']);
     $data['LastDate'] = $end->format("D, M d, Y");
   return array(json_encode($data_points, true),$data['MaxLow'],nth);
}
public function caller(){
    list($chart, $MaxLow,.,nth) = $this->historicalxch($arg);
    $data['chart']=$chart;
    $data['Open']=$AveOpen;
    echo json_encode($data);
    unset($data);
    exit();
}

我想知道如果不手动设置list返回的次数为list的次数,我怎么能有无限的日期返回。

您只需返回一个数组(可以包含任意数量的元素),然后在调用函数中检查数组中的元素数量,并根据需要继续操作。显然,您将无法使用list()语法,因为这需要您在编程时知道将返回多少日期。

function historicalxch ($arg) {
  //some code here creates an array of 10,000 dates
  return $array_of_dates;
}
function caller ($arg) {
  $array_of_dates = historicalxch($arg);
  $number_of_dates = count($array_of_dates);
  foreach($array_of_dates as $date) {
    //do something with each date
  }
}

也可以为更复杂的数据返回关联数组。例如:

function historicalxch ($arg) 
  return array(
    'json' => $json_data,
    'date_array' => $date_array,
    'error' => null
  );
}
function caller ($arg) {
  $data_structure = historicalxch($arg);
  if ($data_structure['error']) {
    die($data_structure['error']);
  }
  foreach($data_structure['date_array'] as $date) {
    //do something with each date
  }
  print($data_structure['json']);
}

如果您想编写真正可靠、可重复使用的代码,而不是关联数组,那么您可以创建一个自定义类,定义返回值所需的数据元素。然后指定该函数返回该类的实例,然后客户端函数可以使用类方法来检索所需的数据。这是一个很大的额外代码开销,但允许严格执行返回值的数据类型,因此,如果您在不更新使用该输出的代码的情况下更改函数的输出,它可能会被php lint或IDE捕获为错误,而不是运行时错误。

返回一个Association数组:(或者甚至只是一个数组,如果调用方知道会发生什么!)

private function historicalxch($args) {
    return array(
         nth=>$nth,
         data_points=>$dataPoints, ... );
}

或者,您可以对预期内容进行更详细的描述,并打算使用函数参数中的引用返回(如C/C++)

private function historicalxch($args, &$nth, &$dataPoints, &$MaxLow, &$MaxHigh) {
    $nth = 5454;
    $MaxLow = max($data['ArrayLow']);
    $MaxHigh = max($data['ArrayHigh']);
    ...
    ...
    return true; // indicate success.
}
function caller ($arg) {
    if(historicalxch($arg, $nth, $dataPoints, $maxLow, $maxHigh)){
         //use your returned $nth, $dataPoints, $maxLow, $maxHigh
    }
}