This article is an original article of Joshua 317. Please note: reprinted from Joshua 317 blog https://www.joshua317.com/article/190
Through the parameter list, you can pass information to the function, that is, a list of expressions separated by commas. Parameters are evaluated from left to right.
PHP supports passing parameters by value (default), passing parameters and default parameters by reference. Variable length parameter lists are also supported
1, Pass parameters by value
Example of passing parameters directly by value
<?php function sum($a, $b) { return $a + $b; } echo sum(1,2);//3
?>
2, Pass parameters by reference
By default, function parameters are passed by value (so even if you change the value of the parameter inside the function, it does not change the value outside the function). If you want to allow a function to modify its parameter values, you must pass parameters by reference.
If you want a parameter of a function to always be passed by reference, you can precede the parameter in the function definition with a symbol&
Example of passing function parameters by reference
<?php function add_some_extra(&$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str;// outputs 'This is a string, and something extra.' ?>
3, The value of the default parameter
The function can define the default values of scalar parameters in C + + style, as shown below:
<?php function makeCoffee($type = "cappuccino") { return "Making a cup of $type.\n"; } echo makecoffee(); echo makecoffee(null); echo makecoffee("espresso"); //The output result is //Making a cup of cappuccino. //Making a cup of . //Making a cup of espresso. ?>
PHP also allows the use of arrays * * array * * and special types NULL As the default parameter, for example:
Use a non scalar type as the default parameter
<?php function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker; return "Making a cup of ".join(", ", $types)." with $device.\n"; } echo makecoffee(); echo makecoffee(array("cappuccino", "lavazza"), "teapot"); ?>
The default value must be a constant expression, not a variable, class member, or function call.
Note that when using default parameters, any default parameters must be placed on the right side of any non default parameters; Otherwise, the function will not work as expected
Since PHP 5, the parameters passed to reference can also have default values.
The following is the wrong usage
<?php function makeyogurt($type = "acidophilus", $flavour) { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt("raspberry"); // won't work as expected //The above routine will output: /** Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/phptest/functest.html on line 41 Making a bowl of raspberry . **/ ?>
4, Variable number of parameter lists
PHP supports a variable number of parameter lists in user-defined functions. In PHP 5.6 and above, it is implemented by... Syntax; In PHP 5.5 and earlier, use the func function_ num_ args(),func_get_arg(), and func_get_args() .
In PHP 5.6 and later, the parameter list may include... Tags indicating that the function accepts a variable number of parameters. The parameter will be passed to the given variable in the form of array;
Use... To accept variable parameters
<?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4);//10 echo sum(1, 2, 3, 4,5);//15 ?>
You can also use... When calling a function to parse an array or traversable variable or character into a parameter list
<?php function add($a, $b) { return $a + $b; } echo add(...[1, 2])."\n";//Output 3 $a = [1, 2]; echo add(...$a);//Output 3 ?>
Accessing variable parameters in PHP 5.5 and earlier
<?php function sum() { $acc = 0; foreach (func_get_args() as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4);//10 ?>
5, Parameter type declaration
Note:
In PHP 5, type declarations are also called type hints.
Type declarations allow functions to call with parameters of a specific type. If the given value type is wrong, an error will be generated: in PHP 5, this will be a recoverable fatal error, and a TypeError exception will be thrown in PHP 7.
In order to specify a type declaration, the type should be added before the parameter name. This declaration can be implemented by setting the default value of the parameter to * * NULL, allowing NULL * * to be passed.
Warning
Aliases of the above scalar types are not supported. Instead, they are treated as class names or interface names. For example, using boolean as a formal parameter or return type will require that the argument or return value be an instance of a class or interface boolean, not a bool ean type:
<?php function test(boolean $param) {} test(true); //The above routine will output: /** Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1 **/ ?>
5.1 type declaration of basic classes
<?php class C {} class D extends C {} // This doesn't extend C. class E {} function f(C $c) { echo get_class($c)."\n"; } f(new C); f(new D); f(new E); ?> Output results: C D Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8 Stack trace: #0 -(14): f(Object(E)) #1 {main} thrown in - on line 8
5.2 type declaration of basic interface
<?php interface I { public function f(); } class C implements I { public function f() {} } // This doesn't implement I. class E {} function f(I $i) { echo get_class($i)."\n"; } f(new C); f(new E); /** Output results: C Fatal error: Uncaught TypeError: Argument 1 passed to f() must implement interface I, instance of E given, called in - on line 13 and defined in -:8 Stack trace: #0 -(13): f(Object(E)) #1 {main} thrown in - on line 8 **/ ?>
5.3 empty type declaration
<?php class C {} function f(C $c = null) { var_dump($c); } f(new C); f(null); /** Output results: object(C)#1 (0) { } NULL **/ ?>
6, Strict type
By default, if you can, PHP will force the value of the wrong type to be the scalar type expected by the function. For example, a parameter of a function is expected to be a string, but an integer is passed in, and the final function will get a value of type string.
Strict mode can be turned on based on each file. In strict mode, only a variable that exactly matches the type declaration will be accepted, otherwise a TypeError will be thrown. The only exception is that you can pass integer to a function that expects float.
Using declare statement and strict_types Declare to enable strict mode
Careful operation
Enabling strict mode also affects return value type declarations
Note:
Strict types apply to function calls in a file with strict mode enabled, not functions declared in that file. If a function defined in the file with strict mode enabled is called in a file without strict mode enabled, the caller's preference (weak type) will be followed, and this value will be converted.
Note:
Strict types are only used for scalar type declarations, which is why PHP 7.0.0 or later is required, because scalar type declarations are also added in that version.
6.1 examples of strict types
<?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)); /** Output results: int(3) Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4 Stack trace: #0 -(9): sum(1.5, 2.5) #1 {main} thrown in - on line 4 **/ ?>
6.2 examples of weak types
<?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)); /** Result output: int(3) int(3) **/ ?>
6.3 capture TypeError example
<?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(); } /** Result output: int(3) Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10 **/ ?>
This article is an original article of Joshua 317. Please note: reprinted from Joshua 317 blog https://www.joshua317.com/article/190