PHP functions support returning various data types, including basic types (Boolean values, integers, floating point numbers, strings), composite types (arrays, objects), resource types (file handles, database handles), null values (NULL ) and void (introduced in PHP 8).
Return value type of PHP function
PHP function can return various data types, including:
Actual case:
Function that returns a Boolean value:
<?php function is_prime(int $number): bool { // 对于 1 和 2,返回真 if ($number <= 2) { return true; } // 遍历 2 到 number 的平方根 for ($i = 2; $i <= sqrt($number); $i++) { if ($number % $i == 0) { return false; } } return true; }
Function that returns an array:
<?php function get_employee_data(int $employee_id): array { // 从数据库中查询员工数据 $result = $mysqli->query("SELECT * FROM employees WHERE id = $employee_id"); // 将结果封装到数组中 $employee_data = $result->fetch_assoc(); return $employee_data; }
Function that returns an object :
<?php class Employee { public $id; public $name; public $department; } function create_employee(string $name, string $department): Employee { $employee = new Employee(); $employee->name = $name; $employee->department = $department; return $employee; }
Function that returns null value:
<?php function get_file_contents(string $filename): ?string { if (file_exists($filename)) { return file_get_contents($filename); } return null; }
Note:
The above is the detailed content of What types of return values do PHP functions have?. For more information, please follow other related articles on the PHP Chinese website!