Returning values

Examples:
Use of return
1
2
3
4
5
6
7
<?php
function square($num)
{
    return $num $num;
}
echo square(4);   // outputs '16'.
?>
Returning an array to get multiple values

A function can not return multiple values, but similar results can be obtained by returning an array.

1
2
3
4
5
6
7
<?php
function small_numbers()
{
    return array (0, 1, 2);
}
list ($zero$one$two) = small_numbers();
?>
Returning a reference from a function

To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:

1
2
3
4
5
6
7
8
<?php
function &returns_reference()
{
    return $someref;
}
 
$newref =& returns_reference();
?>
Basic return type declaration
1
2
3
4
5
6
7
8
<?php
function sum($a$b): float {
    return $a $b;
}
 
// Note that a float will be returned.
var_dump(sum(1, 2));
?>

The above example will output:

float(3)
Strict mode in action
1
2
3
4
5
6
7
8
9
10
<?php
declare(strict_types=1);
 
function sum($a$b): int {
    return $a $b;
}
 
var_dump(sum(1, 2));
var_dump(sum(1, 2.5));
?>

The above example will output:

int(3)

Fatal error: Uncaught TypeError: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5
Stack trace:
#0 -(9): sum(1, 2.5)
#1 {main}
  thrown in - on line 5
Returning an object
1
2
3
4
5
6
7
8
9
<?php
class C {}
 
function getC(): C {
    return new C;
}
 
var_dump(getC());
?>

The above example will output:

object(C)#1 (0) {
}
doc_php
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.