php函数可以返回各种数据类型,包括整数、浮点数、字符串、布尔值、数组、对象和null。具体方法包括:返回整数:使用int类型提示和返回语句;返回浮点数:使用float类型提示和返回语句;返回字符串:使用string类型提示和返回语句;返回布尔值:使用bool类型提示和返回语句;返回数组:使用array类型提示和返回语句;返回对象:创建对象并返回它;返回null:使用?类型提示和返回语句。
PHP 函数返回的数据类型
在 PHP 中,函数可以返回各种数据类型,包括:
- 整数(int)
- 浮点数(float)
- 字符串(string)
- 布尔值(bool)
- 数组(array)
- 对象(object)
- NULL
实战案例
来看看如何定义返回不同数据类型的函数:
<?php
// 返回整数
function sum(int $a, int $b): int
{
return $a + $b;
}
// 返回浮点数
function average(float $a, float $b): float
{
return ($a + $b) / 2;
}
// 返回字符串
function greet(string $name): string
{
return "Hello, $name!";
}
// 返回布尔值
function isOdd(int $number): bool
{
return $number % 2 != 0;
}
// 返回数组
function getNames(): array
{
return ["John", "Mary", "Bob"];
}
// 返回对象
class Person
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
function createPerson(string $name): Person
{
return new Person($name);
}
// 返回 NULL
function getOptionalData(): ?string
{
// 根据某些条件返回数据或 NULL
if (rand(0, 1)) {
return "Data";
}
return null;
}
// 调用函数
$result1 = sum(1, 2); // 整数
$result2 = average(3.5, 5.5); // 浮点数
$result3 = greet("Alice"); // 字符串
$result4 = isOdd(7); // 布尔值
$result5 = getNames(); // 数组
$result6 = createPerson("Bob"); // 对象
$result7 = getOptionalData(); // NULL
// 打印结果类型
echo gettype($result1) . "n";
echo gettype($result2) . "n";
echo gettype($result3) . "n";
echo gettype($result4) . "n";
echo gettype($result5) . "n";
echo gettype($result6) . "n";
echo gettype($result7) . "n";
?>
输出结果:
integer
double
string
boolean
array
object
NULL