Home  >  Article  >  Backend Development  >  PHP function variable scope and function return value tutorial

PHP function variable scope and function return value tutorial

高洛峰
高洛峰Original
2016-11-29 15:07:011212browse

In PHP, regarding variables defined in a function, variables outside the function, including parameters, cannot be accessed, and by default, variables defined outside a function cannot access function variables.

Look at the example below, The code is as follows:

$a = 1;

$b = 2;

function Sum()

{

global $a, $b;

$b = $a + $ b;

}

Sum();

echo $b;

?>

The value of $b returned is 3. In php, global is a global variable, so this is the case, so let’s do it now Look at the php variable reference example, the code is as follows:

function str_unite (&$string)

{

  $string .= 'Also like blue.';

}

$str = ' Like red, ';

str_unite ($str);

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

?>

The above is about the scope of the function References to global variables and functions. Let’s look at the local variables of a function. The code is as follows:

$a = 1;

$b = 2;

function Sum($a,$b)

{//Open source code phpfensi.com

$b = $a + $b;

echo $b;//3

}

Sum();//

echo $b;/ /2

?>


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