PHP 7.1.0 Released

Valori restituiti

I valori vengono restituiti usando l'istruzione opzionale return. Può essere restituito qualsiasi tipo, incluse liste ed oggetti. Ciò provoca l'interruzione dell'esecuzione della funzione immediatamente e la restituzione del controllo alla linea da cui è stata chiamata. Vedere return per maggiori informazioni.

Nota:

Se return è omesso, verrà restituito il valore NULL.

Example #1 Esempio di uso di return

<?php
function quadrato ($num)
{
    return 
$num $num;
}
echo 
quadrato(4);   // L'output è '16'.
?>

Non possono essere restituiti valori multipli da una funzione, ma risultati simili possono essere ottenuti restituendo un array.

Example #2 Restituzione di un array per ottenere più valori

<?php
function numeri_piccoli()
{
    return array (
012);
}
list (
$zero$uno$due) = numeri_piccoli();
?>

Per restituire un riferimento da una funzione, è necessario usare l'operatore di passaggio per riferimento & in entrambe le dichiarazioni di funzioni e quando viene assegnato il valore restituito ad una variabile:

Example #3 Restituzione di un riferimento ad una funzione

<?php
function &restituisce_riferimento()
{
    return 
$un_riferimento;
}

$nuovo_riferimento =& restituisce_riferimento();
?>

Per maggiori informazioni sui riferimenti, consultare References Explained.

add a note add a note

User Contributed Notes 9 notes

up
23
rstaveley at seseit dot com
6 years ago
Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that  pass by value is used for arrays just like scalars. Objects are implicitly passed by reference.

<?php

# (1) Objects are always passed by reference and returned by reference

class Obj {
    public
$x;
}

function
obj_inc_x($obj) {
   
$obj->x++;
    return
$obj;
}

$obj = new Obj();
$obj->x = 1;

$obj2 = obj_inc_x($obj);
obj_inc_x($obj2);

print
$obj->x . ', ' . $obj2->x . "\n";

# (2) Scalars are not passed by reference or returned as such

function scalar_inc_x($x) {
   
$x++;
    return
$x;
}

$x = 1;

$x2 = scalar_inc_x($x);
scalar_inc_x($x2);

print
$x . ', ' . $x2 . "\n";

# (3) You have to force pass by reference and return by reference on scalars

function &scalar_ref_inc_x(&$x) {
   
$x++;
    return
$x;
}

$x = 1;

$x2 =& scalar_ref_inc_x($x);    # Need reference here as well as the function sig
scalar_ref_inc_x($x2);

print
$x . ', ' . $x2 . "\n";

# (4) Arrays use pass by value sematics just like scalars

function array_inc_x($array) {
   
$array{'x'}++;
    return
$array;
}

$array = array();
$array['x'] = 1;

$array2 = array_inc_x($array);
array_inc_x($array2);

print
$array['x'] . ', ' . $array2['x'] . "\n";

# (5) You have to force pass by reference and return by reference on arrays

function &array_ref_inc_x(&$array) {
   
$array{'x'}++;
    return
$array;
}

$array = array();
$array['x'] = 1;

$array2 =& array_ref_inc_x($array); # Need reference here as well as the function sig
array_ref_inc_x($array2);

print
$array['x'] . ', ' . $array2['x'] . "\n";
up
14
nick at itomic.com
13 years ago
Functions which return references, may return a NULL value. This is inconsistent with the fact that function parameters passed by reference can't be passed as NULL (or in fact anything which isnt a variable).

i.e.

<?php

function &testRet()
{
    return
NULL;
}

if (
testRet() === NULL)
{
    echo
"NULL";
}
?>

parses fine and echoes NULL
up
16
bgalloway at citycarshare dot org
8 years ago
Be careful about using "do this thing or die()" logic in your return lines.  It doesn't work as you'd expect:

<?php
function myfunc1() {
    return(
'thingy' or die('otherthingy'));
}
function
myfunc2() {
    return
'thingy' or die('otherthingy');
}
function
myfunc3() {
    return(
'thingy') or die('otherthingy');
}
function
myfunc4() {
    return
'thingy' or 'otherthingy';
}
function
myfunc5() {
   
$x = 'thingy' or 'otherthingy'; return $x;
}
echo
myfunc1(). "\n". myfunc2(). "\n". myfunc3(). "\n". myfunc4(). "\n". myfunc5(). "\n";
?>

Only myfunc5() returns 'thingy' - the rest return 1.
up
11
ryan dot jentzsch at gmail dot com
1 year ago
PHP 7 return types if specified can not return a null.
For example:
<?php
declare(strict_types=1);

function
add2ints(int $x, int $y):int
{
   
$z = $x + $y;
    if (
$z===0)
    {
        return
null;
    }
    return
$z;
}
$a = add2ints(3, 4);
echo
is_null($a) ? 'Null' : $a;
$b = add2ints(-2, 2);
echo
is_null($b) ? 'Null' : $b;
exit();

Output:
7
Process finished with
exit code 139
up
-1
ortreum
13 days ago
I like this method of concatinating methods by returning $this. It makes my code more readable. If the returned value is not an object it will fail and you find mistakes easier.

<?php
class Dummy {

    private
$result;

    function
__construct()
    {
       
$this->result =
           
$this
               
->setStuff('abc')
                ->
generateResult()
            ;
    }
   
    function
setStuff($value)
    {
       
// do something
       
return $this;
    }

    function
generateResult()
    {
        return [
'the result'];
    }

    function
getResult()
    {
        return
$this->result;
    }

}
?>
up
-1
Nathan Salter
1 year ago
Just a quick clarification on whether variables are passed by reference or not. Variables are always passed using a pointer, and if the variable is modified, it is copied and re-assigned. For example:

<?php

function byPointer($x) {
    return
$x / 3; // Does not modify or create a copy of $x
}

function
copied($x) {
   
$x++; // At this point, creates a copy of $x to be used in local scope
   
return $x;
}

class
Obj {
    public function
performAction() {}
    public
$y;
}

function
objPointer(Obj $x) {
   
$x->performAction(); //works on $x
   
$x->y = '150'; //works on $x
   
$x = new Obj(); // Does not modify $x outside of function
   
$x->y = '250';
}

function
objReference(Obj &$x) {
   
$x->performAction(); //works on $x
   
$x->y = '150'; //works on $x
   
$x = new Obj(); // Modifies original $x outside of function
   
$x->y = '250';
}

$x = new Obj();
$x->y = '10';

objPointer($x);

echo
"Post Pointer: {$x->y}\n";

$x->y = '10';
objReference($x);

echo
"Post Reference: {$x->y}\n";

?>

This will output:
Post Pointer: 150
Post Reference: 250

So make sure when writing functions that if you want to pass by reference you actually mean by reference, and not using standard PHP pointers
up
-1
Vidmantas Maskoliunas
7 months ago
Note: the function does not have "alternative syntax" as if/endif, while/endwhile, and colon (:) here is used to define returning type and not to mark where the block statement begins.
up
-3
ian at NO_SPAM dot verteron dot net
13 years ago
In reference to the poster above, an additional (better?) way to return multiple values from a function is to use list(). For example:

function fn($a, $b)
{
   # complex stuff

   return array(
      $a * $b,
      $a + $b,
   );
}

list($product, $sum) = fn(3, 4);

echo $product; # prints 12
echo $sum; # prints 7
up
-25
Anonymous
6 years ago
As of at least PHP 5.3, a function or class method returning an object acts like an object.

<?php

class A {
    function
test() {
        echo
"Yay!";
        }
    }

function
get_obj() {
    return new
A();
    }

get_obj()->test();  // "Yay!"

?>

Sorry, still doesn't work with arrays.  Ie <?php echo get_array()[1]; ?> fails.
To Top