Home >Backend Development >PHP Tutorial >php function and passing parameters

php function and passing parameters

高洛峰
高洛峰Original
2016-11-29 15:08:131211browse

This tutorial will introduce the syntax of function calling and function definition, and talk about variables in functions and methods of passing numerical values ​​to functions.

1. The basis of functions

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

function myCount($inValue1,$inValue2)

{

$AddValue = $inValue1+$inValue2;

return $AddValue; //Return the calculation result

}

$Count = myCount(59,100);

echo $Count; //Output 159

?>

Once the function is defined, it can be used anywhere.

2. Function parameters

PHP function parameters are declared and defined when the function is defined. The function can have any number of parameters. The most commonly used transfer method is to pass by value, or relatively rarely through reference and default parameter values. The example code is as follows :

function myColor ($inColor = "blue")

{

  return "The color I like: $inColor. ";

}

echo myColor();

echo myColor("pink");

?>

Generally, the value passed will not change due to internal changes in the function, unless it is a global variable or a reference. Let's look at the PHP function reference example. The code is as follows:

< ?php

function str_unite (&$string)

{

$string .= 'Also like blue.';

}

$str = 'Like red,';

str_unite ($str);

echo $str; // Output result: 'Like red, also like blue.'

?>

global variable, the code is as follows:

$a = 1;

$ b = 2;

function Sum()

{//open source code phpfensi.com

global $a, $b;

$b = $a + $b;

}

Sum();

echo $b;

?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn