- PHP/Functions/Return Value
- Passing Arguments and Returning Values by Reference
- Returning a list an array from function
- Returning an array from a function
- Returning a Value by Reference
- Returning a value from a function
- Returning by Reference
- Returning More Than One Value
- Returning Values by Reference
- return multiple values from a function
- User-Defined Function to Determine a Leap Year
- Using an array returned from a function
- Возврат значений
- Использование выражения return
- Объявление типов возвращаемых значений
- Примеры
- PHP function/method returning boolean result and a status message
- Php return array or false
PHP/Functions/Return Value
Passing Arguments and Returning Values by Reference
> $mynum = 5; $output = add2($mynum); $output++;
$new = array_fill(0, 10, array_fill(0, 10, 0)); return $new;
> $newarray =& initialize(); echo print_r($newarray, true); ?>
Returning a list an array from function
> list ($zero, $one, $two) = small_numbers(); ?>
Returning an array from a function
$tax_amount = $meal * ($tax / 100); $tip_amount = $meal * ($tip / 100); $total_notip = $meal + $tax_amount; $total_tip = $meal + $tax_amount + $tip_amount; return array($total_notip, $total_tip);
Returning a Value by Reference
function &find_var($one, $two, $three) < if(($one >0) && ($one 0) && ($two 0) && ($three $c_one = "foo"; $c_two = 42; $c_three = 4; $right_var = &find_var($c_one, $c_two, $c_three); $right_var++; echo "The value of \$c_three and \$right_var are: "; echo "$c_three and $right_var
\n";
Returning a value from a function
$tax_amount = $meal * ($tax / 100); $tip_amount = $meal * ($tip / 100); $total_amount = $meal + $tax_amount + $tip_amount; return $total_amount;
Returning by Reference
$fish = "Wanda"; return $fish; > $fish_ref =& return_fish( );
Returning More Than One Value
$firstreturnvalue = ($firstvalue + $secondvalue); $secondreturnvalue = ($firstvalue - $secondvalue); $myarray = array (); $myarray[0] = $firstreturnvalue; $myarray[1] = $secondreturnvalue; return $myarray;
> $myarray = array (); $myarray = addandsubtract (10, 3); echo $myarray[0] . «
«; echo $myarray[1]; ?>
Returning Values by Reference
private $thevalue; private $theword; public function __construct () < $num_args = func_num_args(); if($num_args >0)< $args = func_get_args(); $this->theword = $args[0]; > > public function setvalue ($newvalue)< $this->thevalue = $newvalue; > public function getvalue () < return $this->thevalue; > public function getword () < return $this->theword; >
> $myclass1 = new myclass («A»); $myclass1->setvalue (1);
$myclass2 = new myclass («B»); $myclass2->setvalue (2);
$myclass3 = new myclass («C»); $myclass3->setvalue (3);
$myclass4 = new myclass («D»); $myclass4->setvalue (4);
$classarr = array ($myclass1,$myclass2,$myclass3,$myclass4); function &findclass ($whichclass,$classarr)
for ($i = 0; $i < count ($classarr); $i++)< if ($classarr[$i]->getvalue() == $whichclass) < return $classarr[$i]; >>
> $myobject = new myclass («»); $myobject =& findclass (3,$classarr); echo $myobject->getword(); ?>
return multiple values from a function
function retrieve_user_profile() < $user[] = "Jason"; $user[] = "jason@example.ru"; $user[] = "English"; return $user; >list($name,$email,$language) = retrieve_user_profile(); echo "Name: $name, email: $email, preferred language: $language";
User-Defined Function to Determine a Leap Year
function is_leapyear($year = 2004) < $is_leap = (!($year % 4) && (($year % 100) || !($year % 400))); return $is_leap; >$answer = is_leapyear(2000); if($answer) < echo "2000 is a leap year
"; > else < echo "2000 is not a leap year.
"; > $answer = is_leapyear(); if($answer) < echo "2003 is a leap year.
"; > else < echo "2003 is not a leap year.
"; >
Using an array returned from a function
$tax_amount = $meal * ($tax / 100); $tip_amount = $meal * ($tip / 100); $total_notip = $meal + $tax_amount; $total_tip = $meal + $tax_amount + $tip_amount; return array($total_notip, $total_tip);
> $totals = myFunction2(15.22, 8.25, 15); if ($totals[0] < 20)
print «The total without tip is less than $20.»;
print "The total with tip is less than $20.";
Возврат значений
Значения возвращаются при помощи необязательного оператора возврата. Возвращаемые значения могут быть любого типа, в том числе это могут быть массивы и объекты. Возврат приводит к завершению выполнения функции и передаче управления обратно к той строке кода, в которой данная функция была вызвана. Для получения более детальной информации ознакомьтесь с описанием return .
Замечание:
Если конструкция return не указана, то функция вернет значение NULL .
Использование выражения return
Пример #1 Использование конструкции return
Функция не может возвращать несколько значений, но аналогичного результата можно добиться, возвращая массив.
Пример #2 Возврат нескольких значений в виде массива
function small_numbers ()
return array ( 0 , 1 , 2 );
>
list ( $zero , $one , $two ) = small_numbers ();
?>?php
Для того, чтобы функция возвращала результат по ссылке, вам необходимо использовать оператор & и при описании функции, и при присвоении переменной возвращаемого значения:
Пример #3 Возврат результата по ссылке
Для получения более детальной информации о ссылках обратитесь к разделу документации Подробно о ссылках.
Объявление типов возвращаемых значений
В PHP 7 добавлена возможность объявлять тип возвращаемого значения. Аналогично объявлению типов аргументов можно задать тип значения, которое будет возвращаться функцией. Типы, которые можно объявить для возвращаемых значений те же, что и для аргументов фукнций.
Режим строгой типизации также работает для объявлении типа возвращаемого значения. В обычном режиме слабой типизации возвращаемое из функции значение приводится к корректному типу. При строгой типизации возвращаемое значение должно быть заданного типа, иначе будет выброшено исключение TypeError.
Замечание:
Если переопределяется родительский метод, возвращаемое значение дочернего метода должно быть того же типа, что и родительского. Если в родительском методе не задан тип возвращаемого значения, то и дочерний метод этот тип может не объявлять.
Примеры
Пример #4 Обычное объявление типа возвращаемого значения
// Будет возвращаться значение типа float.
var_dump ( sum ( 1 , 2 ));
?>
Результат выполнения данного примера:
Пример #5 То же в режиме строгой типизации
function sum ( $a , $b ): int return $a + $b ;
>
var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1 , 2.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 thrown in - on line 5
Пример #6 Возврат объектов
function getC (): C return new C ;
>
Результат выполнения данного примера:
PHP function/method returning boolean result and a status message
I have a class with methods that need to return their result status (true|false) and also return a status message («It worked/did not work because of x. «). Here are the two approaches I’ve tried. Approach # 1: Return boolean and pass message by reference Example of function:
function do_something ($arg1, $arg2, &$message) < . do stuff resulting success. // Give an explanation for why it succeeded. reasons could be varied: $message = 'It succeeded and here are your instructions for celebrating: . '; $success = true; . do stuff resulting in failure. // Give an explanation for why it failed. reasons could be varied: $message = 'it failed because of so and so. '; $success = false; return $success; >
$message = ''; if ( do_something($arg1, $arg2, $message) ) < echo "It succeeded because $message."; >else
function do_something ($arg1, $arg2) < . do stuff. // Give an explanation for why it succeeded. reasons could be varied: $message = 'It succeeded and here are your instructions for celebrating: . '; $success = true; . do stuff. // Give an explanation for why it failed. reasons could be varied: $message = 'it failed because of so and so. '; $success = false; return new Result($success, $message); >
You can imagine what the class definition of Result would like like, so I’ll spare the example. Example of call:
$message = ''; $DoSomething = do_something($arg1, $arg2, $message); if ( $DoSomething->success ) < echo "It succeeded because ". $DoSomething->message; > else < echo "It failed because ". $DoSomething->message; >
Php return array or false
While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.
PHP 5.6 added the splat operator (. ) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.
function typeArrayNullInt (? int . $arg ): void >
function doSomething (array $ints ): void (function (? int . $arg ) <>)(. $ints );
// Alternatively,
( fn (? int . $arg ) => $arg )(. $ints );
// Or to avoid cluttering memory with too many closures
typeArrayNullInt (. $ints );
function doSomethingElse (? int . $ints ): void /* . */
>
$ints = [ 1 , 2 , 3 , 4 , null ];
doSomething ( $ints );
doSomethingElse (. $ints );
?>
Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething’s method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.
If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.
same data type and same value but first function declare as a argument type declaration and return int(7)
and second fucntion declare as a return type declaration but return int(8).
function argument_type_declaration(int $a, int $b) return $a+$b;
>
function return_type_declaration($a,$b) :int return $a+$b;
>