Funktionen
PHP Manual

Rückgabewerte

Sie können Werte mit dem optionalen Befehl "return" zurückgeben. Es können Variablen jeden Typs zurückgegeben werden, auch Arrays oder Objekte. Dies beendet sofort die Funktion und die Kontrolle wird wieder an die aufrufende Zeile zurückgegeben. Weitere Informationen finden Sie unter return.

Hinweis:

Wird return ausgelassen, dann wird der Wert NULL zurückgegeben.

Einsatz von return

Beispiel #1 Einsatz von return

<?php
function quadrat($zahl)
{
    return 
$zahl $zahl;
}
echo 
quadrat(4);   // gibt '16' aus.

?>

Es ist nicht möglich, mehrere Werte von einer Funktion zurückzugeben. Ein ähnliches Resultat kann man aber durch die Rückgabe eines Arrays erreichen.

Beispiel #2 Rückgabe mehrere Werte in Arrays

<?php
function kleine_zahlen()
{
   return array (
012);
}
list (
$null$eins$zwei) = kleine_zahlen();
?>

Um von einer Funktion eine Referenz zurückzugeben, müssen Sie den Referenz-Operator & sowohl in der Funktionsdeklaration, als auch bei der Zuweisung des zurückgegebenen Wertes verwenden:

Beispiel #3 Rückgabe von Referenzen

<?php
function &returniere_referenz()
{
    return 
$einereferenz;
}

$neuereferenz =& returniere_referenz();
?>

Weitere Informationen über Referenzen finden Sie im Kapitel Referenzen in PHP.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

Hinweis:

When overriding a parent method, the child's method must match any return type declaration on the parent. If the parent doesn't define a return type, then the child method may do so.

Beispiele

Beispiel #4 Basic return type declaration

<?php
function sum($a$b): float {
    return 
$a $b;
}

// Note that a float will be returned.
var_dump(sum(12));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

float(3)

Beispiel #5 Strict mode in action

<?php
declare(strict_types=1);

function 
sum($a$b): int {
    return 
$a $b;
}

var_dump(sum(12));
var_dump(sum(12.5));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #6 Returning an object

<?php
class {}

function 
getC(): {
    return new 
C;
}

var_dump(getC());
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(C)#1 (0) {
}

Funktionen
PHP Manual