Lecture
The function can take information in the form of a list of arguments, which is a comma-separated list of expressions. Arguments are calculated from left to right.
PHP supports passing arguments by value (default), passing arguments by reference, origin by default. Variable length argument lists are also supported; see also function descriptions func_num_args (), func_get_arg (), and func_get_args () for more details.
Example # 1 Passing an array to a function
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
By default, the arguments to the function are passed by value (this means that if you change the value of the argument inside the function, then its value will still remain the same). If you want to allow functions to modify their arguments, you must pass them by reference.
If you want the argument to always be passed by reference, you can specify an ampersand (&) before the argument name in the function description:
Example # 2 Passing Arguments by Reference
<?php
function add_some_extra(&$string)
{
$string .= 'и кое-что еще.';
}
$str = 'Это строка, ';
add_some_extra($str);
echo $str; // выведет 'Это строка, и кое-что еще.'
?>
The function can define default C ++ style values for scalar arguments, for example:
Example # 3 Using default values in a function definition
<?php
function makecoffee($type = "капуччино")
{
return "Готовим чашку $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("эспрессо");
?>
The result of this example:
Cooking a cup of cappuccino. Cooking a cup. Cooking a cup of espresso.
PHP also allows the use of arrays (array) and the special type NULL
as default values, for example:
Example # 4 Using non-scalar types as default values
<?php
function makecoffee($types = array("капуччино"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "вручную" : $coffeeMaker;
return "Готовлю чашку ".join(", ", $types)." $device.\n";
}
echo makecoffee();
echo makecoffee(array("капуччино", "лавацца"), "в чайнике");
?>
The default value must be a constant expression, and not (for example) a variable or a call to a function / method of a class.
Please note that all the arguments for which default values are set should be to the right of the arguments for which no default values are specified, otherwise your code may not work as expected. Consider the following example:
Example # 5 Incorrect use of default values
<?php
function makeyogurt($type = "ацидофил", $flavour)
{
return "Готовим чашку из бактерий $type со вкусом $flavour.\n";
}
echo makeyogurt("малины"); // Не будет работать так, как мы могли бы ожидать
?>
The result of this example:
Warning: Missing argument 2 in call to makeyogurt () in /usr/local/etc/httpd/htdocs/phptest/functest.html on line 41 Cooking a cup of raspberry bacteria with taste.
Now compare it with the following example:
Example # 6 Proper use of default values
<?php
function makeyogurt($flavour, $type = "ацидофил")
{
return "Готовим чашку из бактерий $type со вкусом $flavour.\n";
}
echo makeyogurt("малины"); // отрабатывает правильно
?>
The result of this example:
Prepare a cup of bacteria acidophilus with raspberry flavor.
Note: Starting with PHP 5, default values can be passed by reference.
Comment:
Type declaration is also known as hints for types in PHP 5.
Type declarations allow functions to strictly specify the type of parameters passed. Passing values of an inappropriate type to a function will result in an error: in PHP 5 this will be a fatal error handled, and in PHP 7 a TypeError exception will be thrown.
To declare the type of the argument, you must add the name of the required type before its name. You can also declare the type NULL
to indicate that the argument's default value is NULL
.
Type of | Description | Minimal PHP Version |
---|---|---|
Class / interface name | The argument must be instanceof , which is the name of the class or interface. | PHP 5.0.0 |
array | The argument must be of type array. | PHP 5.1.0 |
callable | The argument must be a valid callable type. | PHP 5.4.0 |
bool | The argument must be of type boolean. | PHP 7.0.0 |
float | The argument must be a float type. | PHP 7.0.0 |
int | The argument must be of type integer. | PHP 7.0.0 |
string | The argument must be of type string. | PHP 7.0.0 |
Example # 7 Basic class type declarations
<?php
class C {}
class D extends C {}
// Это не является расширением класса C.
class E {}
function f(C $c) {
echo get_class($c)."\n";
}
f(new C);
f(new D);
f(new E);
?>
The result of this example:
C D Fatal error: Uncaught TypeError: Argument 1; Stack trace: # 0 - (14): f (Object (E)) # 1 {main} thrown in - on line 8
Example # 8 Basic interface type declarations
<?php
interface I { public function f(); }
class C implements I { public function f() {} }
// Это не реализует интерфейс I.
class E {}
function f(I $i) {
echo get_class($i)."\n";
}
f(new C);
f(new E);
?>
The result of this example:
C Fatal error: Uncaught TypeError: Argument 1 passed to the interface and defined in -: 8 Stack trace: # 0 - (13): f (Object (E)) # 1 {main} thrown in - on line 8
Example # 9 Null type declaration
<?php
class C {}
function f(C $c = null) {
var_dump($c);
}
f(new C);
f(null);
?>
The result of this example:
object (C) # 1 (0) { } Null
By default, PHP will attempt to cast non-matching types to a scalar type, if possible. For example, if integer is passed to the function, and the argument type is declared string, the function will eventually receive the converted string value.
For individual files, you can enable strong typing. In this mode, only those types that are declared for arguments can be passed to the function. Otherwise, a TypeError exception will be thrown. There is only one exception - an integer can be passed to a function that expects a value of type float.
To enable strong typing, use the declare expression in the strict_types declaration :
Enabling strong typing will also affect declarations of return types.
Comment:
Strong typing applies to function calls made from the file in which this mode is enabled, and not to the functions that are declared in this file. If a file without strong typing calls a function that is declared in a file with mode enabled, the argument values will be cast to the desired types and no errors will follow.
Comment:
Strong typing applies only to scalar types and works only in PHP 7.0.0 and higher. As well as scalar type declarations themselves are added in this version.
Example # 10 Strong Typing
<?php
declare(strict_types=1);
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>
The result of this example:
int (3) Fatal error: Uncaught TypeError: Argument 1 passed to the sum () Stack trace: # 0 - (9): sum (1.5, 2.5) # 1 {main} thrown in - on line 4
Example # 11 Poor typing
<?php
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum(1, 2));
// These will be coerced to integers: note the output below!
var_dump(sum(1.5, 2.5));
?>
The result of this example:
int (3) int (3)
Example # 12 Handling a TypeError Exception
<?php
declare(strict_types=1);
function sum(int $a, int $b) {
return $a + $b;
}
try {
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
} catch (TypeError $e) {
echo 'Error: '.$e->getMessage();
}
?>
The result of this example:
int (3) Error: Argument 1 passed to sum (), float given, called in - on line 10
PHP supports variable-length argument lists for user-defined functions. For versions of PHP 5.6 and higher, this is done by adding an ellipsis ( ... ). Functions 5.5 and later use the func_num_args (), func_get_arg () and func_get_args () functions.
In versions of PHP 5.6 and above, the argument list may contain an ellipsis ... to show that the function takes a variable number of arguments. Arguments in this case will be passed as an array. For example:
Example # 13 Using ... to access arguments
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
The result of this example:
ten
Ellipsis ( ... ) can be used when calling a function to unpack an array (array) or Traversable variable in the argument list:
Example # 14 Using ... to pass arguments
<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>
The result of this example:
3 3
You can set several arguments in the usual way, and then add .... In this case ... it will put in the array only those arguments that do not find the match specified in the function declaration.
You can also add a hint like before .... In this case, PHP will ensure that all arguments processed by ellipsis ( ... ) are of the same type as indicated in the hint.
Example # 15 Type hint arguments
<?php
function total_intervals($unit, DateInterval ...$intervals) {
$time = 0;
foreach ($intervals as $interval) {
$time += $interval->$unit;
}
return $time;
}
$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';
// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);
?>
The result of this example:
3 days Catchable fatal error: Argument 2 passed to the total_intervals ();
In the end, you can pass arguments by reference. To do this, before ... you need to put an ampersand ( & ).
To indicate that a function takes a variable number of arguments, no special syntax is used. To access the arguments, you must use the func_num_args (), func_get_arg () and func_get_args () functions.
In the first example above, it was shown how to set a list of variable length arguments for versions of PHP 5.5 and earlier:
Example # 16 Access to arguments in PHP 5.5 and earlier versions
<?php
function sum() {
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
The result of this example:
ten
Comments
To leave a comment
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)