Example Analysis of php Function and Transfer Parameters

  • 2021-08-03 09:48:55
  • OfStack

This article describes the example of the function of the call and function definition syntax, and explained about the variables in the function and the transfer of numerical methods to the function. Share for your reference. The details are as follows:

1. Fundamentals of a function

php provides a large number of functions and allows users to customize functions. The example code of php function definition is as follows:

<?php 
function myCount($inValue1,$inValue2)
{
  $AddValue = $inValue1+$inValue2;
  return $AddValue;     // Return the calculation result
}
$Count = myCount(59,100);
echo $Count;     // Output 159
?>

Function 1 is defined and can be used anywhere.

2. Function transfer parameters

php function parameters are declared at the time of function definition. The function can have any number of parameters. The most common passing method is passed by value, or it is applied relatively rarely by reference and default parameter values. The example code is as follows:

<?php 
function myColor ($inColor = " Blue ")
{
    return " My favorite color: $inColor. ";
}
echo myColor();
echo myColor(" Pink ");
?>

The value passed in general will not change due to internal changes of the function, unless it is a global variable or a reference. Let's look at the php function reference instance. The code is as follows:
<?php 
function str_unite (&$string)
{
    $string .= ' I also like blue .';
}
$str = ' I like red, ';
str_unite ($str);
echo $str;    // Output: ' I like red and blue .'
?>

Global variable, code as follows:
<?php 
$a = 1;
$b = 2;
function Sum()
{
    global $a, $b;
    $b = $a + $b;
}
Sum();
echo $b;
?>

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


Related articles: