【问题标题】:How to return an array from a function in PHP?如何从 PHP 中的函数返回数组?
【发布时间】:2018-01-18 20:13:19
【问题描述】:

当我在 return 语句之前转储数组时,一切似乎都很好。 但是,当我转储结果时,它似乎是空的。

应该更清楚包含的代码。我从 DatabaseHandler 调用 GetRow,当我在返回之前进行转储时,我可以看到有一个数组。 (参见 var_dump)

public static function GetRow($sqlQuery, $params = null,
                            $fetchStyle = PDO::FETCH_ASSOC)
 {
// Initialize the return value to null
$result = null;

// Try to execute an SQL query or a stored procedure
try
{
  // Get the database handler
  $database_handler = self::GetHandler();

  // Prepare the query for execution
  $statement_handler = $database_handler->prepare($sqlQuery);

  // Execute the query
  $statement_handler->execute($params);

  // Fetch result
  $result = $statement_handler->fetch($fetchStyle);
}
// Trigger an error if an exception was thrown when executing the SQL query
catch(PDOException $e)
{
  // Close the database handler and trigger an error
  self::Close();
  trigger_error($e->getMessage(), E_USER_ERROR);
}

// Return the query results
  exit(var_dump($result)); // SHOWS A PROPER ARRAY
return $result;
}

在调用它的另一个函数中,什么都看不到(假):

// Gets the details of a specific order
public static function GetOrderInfo($orderId)
{
// Build the SQL query
$sql = 'CALL orders_get_order_info(:order_id)';

// Build the parameters array
$params = array (':order_id' => $orderId);

// Execute the query and return the results
  $result = DatabaseHandler::GetRow($sql, $params);
  exit(var_dump($result)); // SHOWS FALSE
  return $result
}

【问题讨论】:

  • 不要 exit 它永远不要 returns...
  • 在 var_dump 后使用 return 并移除 exit。
  • 这应该被标记为拼写错误
  • exit(var_dump($result)); 将显示var_dump(...) 的返回值(as shown in the documentation 什么都不是)。它不会向您显示与 var_dump($result); exit(); 相同的内容。
  • 谢谢,但是转储只是为了显示变量中的内容。如果我删除所有退出语句, $result 只是错误

标签: php return


【解决方案1】:

不要调用exit。 PHP 中的数组在参数/返回值方面没有什么特别之处 - 问题是您正在以 exit() 调用终止。

【讨论】:

  • 谢谢,但是转储只是为了显示变量中的内容。如果我删除所有退出语句,$result 就是假的。
【解决方案2】:

来自文档http://php.net/manual/en/function.exit.php

终止脚本的执行

换句话说,return 语句是无法访问的。所以你的代码永远不会返回,因为进程在它之前退出。

【讨论】:

  • 谢谢,但是转储只是为了显示变量中的内容。如果我删除所有退出语句, $result 只是错误
  • 这可能是因为您的数据库或 SQL 有问题。此语句返回 false:$statement_handler->fetch($fetchStyle),这就是挖掘更多内容的地方。
  • 当我像这样倾倒它时; $result = $statement_handler->fetch($fetchStyle);退出(var_dump($result));我可以看到数组。
  • 很奇怪,当我在返回之前这样做时它起作用了:$array['customer_id'] = $result['customer_id']; $array['shipping_region_id'] = $result['shipping_region_id']; $array['credit_card'] = $result['credit_card'];返回 $array;
  • var_dump($result) 显示的是数组还是对象?
【解决方案3】:

虽然 PDO 返回了一个数组,但它不能用于 foreach、while 或 json_encode 等函数(无效参数)。

解决方案是使用 MySQLi,它返回完全相同的 Array,只是这次它可用于 foreach、while 或 json_encode 等函数。

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多