PHP 函數 return 僅能返回單一值,但該值可以是陣列/對象,從而實現「返回多個值」的效果。
<?php
function results(string $string): array {
$result = [];
$result[] = $string; // 原字符串
$result[] = strtoupper($string); // 全大寫
$result[] = strtolower($string); // 全小寫
$result[] = ucwords($string); // 首字母大寫
return $result;
}
$multi = results('The quick brown fox jump over the lazy dog');
print_r($multi);
Array
(
[0] => The quick brown fox jump over the lazy dog
[1] => THE QUICK BROWN FOX JUMP OVER THE LAZY DOG
[2] => the quick brown fox jump over the lazy dog
[3] => The Quick Brown Fox Jump Over The Lazy Dog
)
function results(string $string): array {
return [
'original' => $string,
'upper' => strtoupper($string),
'lower' => strtolower($string),
'title' => ucwords($string),
];
}
$r = results('hello world');
echo $r['upper']; // HELLO WORLD
function foo(&$a, &$b) { $a=1; $b=2; } 直接修改外部變量(不推薦,降低可讀性)。function gen() { yield 1; yield 2; } 逐個產出值,適合大數據集。