gpt4 book ai didi

php - 最佳实践 : returning multiple values

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:13 25 4
gpt4 key购买 nike

从纯编码最佳实践的角度,建议采用什么作为大中型开发团队的标准?

返回一个顺序数组:

function get_results($filter) {
$query = "SELECT SQL_CALC_FOUND_ROWS, * FROM ...";

$results = ...
$total = ...

return array($results, $total);
}

返回一个关联数组:

function get_results($filter) {
$query = "SELECT SQL_CALC_FOUND_ROWS, * FROM ...";

$results = ...
$total = ...

return array(
'resuts' => $results,
'total' => $total
);
}

返回单个结果并通过引用分配第二个结果(?!):

function get_results($filter, &$count = null) {
$query = "SELECT SQL_CALC_FOUND_ROWS, * FROM ...";

$results = ...
$total = ...

$count = $total;
return $results;
}

请随意提出任何其他方法。

最佳答案

来自 PHP 文档:

A function can not return multiple values, but similar results can be obtained by returning an array.

根据文档的说明,所有这些看起来都是很好的做法。 comment in the documentation揭示了另一种方式:使用 list()。请参见下面的示例:

function fn($a, $b)
{
# complex stuff

return array(
$a * $b,
$a + $b,
);
}

list($product, $sum) = fn(3, 4);

echo $product; # prints 12
echo $sum; # prints 7

关于php - 最佳实践 : returning multiple values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com