函數返回變量類型:1. 標量類型(int、float、string、bool);2. 引用類型(array、object);3. null 值。
在 PHP 函數中返回不同變量類型的值
在 PHP 函數中,您可以使用不同的變量類型將值返回到調用代碼:
1. 標量類型:
int:整數
float:浮點數
string:字符串
bool:布爾值
用法:
function addNumbers($a, $b) {
return $a + $b; // 返回整數
}
登錄后復制
2. 引用類型:
array:數組object:對象
用法:
function getArray() {
return [1, 2, 3]; // 返回數組
}
登錄后復制
3. null 值:
表示沒有值或未知值
用法:
function checkIfEmpty($value) {
if (empty($value)) {
return null; // 返回 null
} else {
return $value;
}
}
登錄后復制
實戰案例:
考慮一個計算矩形面積的函數:
function calculateArea($length, $width) {
if ($length < 0 || $width < 0) {
return null; // 如果長度或寬度為負,返回 null
} else {
return $length * $width; // 返回矩形面積
}
}
$area = calculateArea(5, 3); // 調用函數,將結果存儲在 $area 中
if ($area !== null) {
echo "矩形面積為 {$area}";
} else {
echo "輸入的長度或寬度為負,無法計算面積";
}
登錄后復制
在這個案例中,calculateArea 函數可以使用 float 類型返回矩形面積,或者使用 null 值表示無效輸入。






