锟斤拷锟斤拷值

值通锟斤拷使锟矫匡拷选锟侥凤拷锟斤拷锟斤拷浞碉拷亍锟斤拷锟斤拷苑锟斤拷匕锟斤拷锟斤拷锟斤拷锟酵讹拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷汀锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟街癸拷锟斤拷锟斤拷锟斤拷锟斤拷校锟斤拷锟斤拷医锟斤拷锟斤拷锟饺拷锟斤拷氐锟斤拷酶煤锟斤拷锟斤拷拇锟斤拷锟斤拷小锟斤拷锟斤拷锟斤拷锟较拷锟� return锟斤拷

Note:

锟斤拷锟绞★拷锟斤拷锟� return锟斤拷锟津返伙拷值为 NULL锟斤拷

return 锟斤拷使锟斤拷

Example #1 return 锟斤拷使锟斤拷

<?php
function square($num)
{
    return 
$num $num;
}
echo 
square(4);   // outputs '16'.
?>

锟斤拷锟斤拷锟斤拷锟杰凤拷锟截讹拷锟街碉拷锟斤拷锟斤拷锟斤拷锟酵拷锟斤拷锟斤拷锟揭伙拷锟斤拷锟斤拷锟斤拷锟斤拷玫锟斤拷锟斤拷频锟叫э拷锟斤拷锟�

Example #2 锟斤拷锟斤拷一锟斤拷锟斤拷锟斤拷锟皆得碉拷锟斤拷锟斤拷锟斤拷锟街�

<?php
function small_numbers()
{
    return array (
012);
}
list (
$zero$one$two) = small_numbers();
?>

锟接猴拷锟斤拷锟斤拷锟斤拷一锟斤拷锟斤拷锟矫o拷锟斤拷锟斤拷锟节猴拷锟斤拷锟斤拷锟斤拷锟斤拷指锟缴凤拷锟斤拷值锟斤拷一锟斤拷锟斤拷锟斤拷时锟斤拷使锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� &锟斤拷

Example #3 锟接猴拷锟斤拷锟斤拷锟斤拷一锟斤拷锟斤拷锟斤拷

<?php
function &returns_reference()
{
    return 
$someref;
}

$newref =& returns_reference();
?>

锟叫癸拷锟斤拷锟矫的革拷锟斤拷锟斤拷息, 锟斤拷榭�锟斤拷锟矫的斤拷锟斤拷锟斤拷

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.

Note:

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.

锟斤拷锟斤拷

Example #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));
?>

锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�

float(3)

Example #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));
?>

锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�

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

Example #6 Returning an object

<?php
class {}

function 
getC(): {
    return new 
C;
}

var_dump(getC());
?>

锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�

object(C)#1 (0) {
}