PHP Function Passing Parameters by Reference and Function Optional Parameters Usage Examples

  • 2021-10-15 10:05:02
  • OfStack

In this paper, an example is given to describe the use of PHP function passing parameters by reference and optional parameters of the function. Share it for your reference, as follows:

1. Functions pass arguments by reference

1. Code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> Pass by reference </title>
</head>
<body>
<?php
function example( &$m ) // Definition 1 Functions, passing arguments at the same time $m Variables of 
{
  $m = $m * 5 + 10;
  echo " Within a function: \$m = ".$m;    // Output the value of the formal parameter 
}
$m = 1;
example( $m ) ;           // Pass value: set the $m To the formal parameter $m
echo "<p> Outside the function: \$m = $m <p>" ;  // The value of the argument changes , Output m=15
?>
</body>
</html>

2. Running results

Within a function: $m = 15
Outside the function: $m = 15

3. Considerations

When passing by reference, it should be noted that there are 1 more arguments in the parameter list of the function than passing by value & .

2. Optional arguments to the function

1. Code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=gb2312"/>
<title> Application of default parameters </title>
</head>
<body>
<?php
function values($price,$tax=""){// Definition 1 Functions, where 1 The initial value of each parameter is empty 
$price=$price+($price*$tax);// Declaration 1 Variable $price Which is equal to the result of the operation for both parameters 
echo " Price :$price<br>";// Output price 
}
values(100,0.25);// Assign values to optional parameters 0.25
values(100);// No value assigned to optional parameter 
?>
</body>
</html>

2. Running results

Price: £ 125
Price: £ 100

3. Considerations

Place the optional parameter at the end of the parameter list and specify that its default value is null.
② When using default parameters, the default parameters must be placed to the right of non-default parameters, otherwise the function may make errors.
③ Starting from PHP5, it can also be passed by reference by default.

For more readers interested in PHP related contents, please check the topics of this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Tutorial on Data Structure and Algorithms of PHP", "Summary of Programming Algorithms of php" and "Complete Collection of Operation Skills of PHP Array (Array)"

I hope this article is helpful to everyone's PHP programming.


Related articles: