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:
-
Scalar type: Boolean, integer, floating point number, string
-
Composite type: Array, object
-
Resources Type: File handle, MySQL connection handle
-
Empty (NULL) type: No clear value
Actual case:
Function that returns a Boolean value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php
function is_prime(int $number ): bool
{
if ( $number <= 2) {
return true;
}
for ( $i = 2; $i <= sqrt( $number ); $i ++) {
if ( $number % $i == 0) {
return false;
}
}
return true;
}
|
Copy after login
Function that returns an array:
1 2 3 4 5 6 7 8 9 10 11 | <?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 ;
}
|
Copy after login
Function that returns an object :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?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 ;
}
|
Copy after login
Function that returns null value:
1 2 3 4 5 6 7 8 9 | <?php
function get_file_contents(string $filename ): ?string
{
if ( file_exists ( $filename )) {
return file_get_contents ( $filename );
}
return null;
}
|
Copy after login
Note:
##PHP 7 and Later versions eliminated all return types except Boolean. - In PHP 8, a new void return type was introduced to indicate that the function does not return any value.
-
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!