php 函数按作用域分类,决定了变量在函数内的可见范围:1. 局部变量仅在函数内可见,使用 $ 声明;2. 全局变量在函数内外部都可见,使用 global 声明;3. 静态变量在函数调用之间保持值,使用 static 声明。
php 函数按作用域分类
函数作用域决定了变量在函数中可以被访问的范围。PHP 中函数按作用域分为三种类型:
1. 局部变量
立即学习“PHP免费学习笔记(深入)”;
只在函数体内可见,在函数外无法访问。局部变量使用 $ 符号声明。
1
2
3
4
5
6
|
function sum( $num1 , $num2 ) {
$result = $num1 + $num2 ;
return $result ;
}
$result = sum(10, 20);
|
2. 全局变量
在函数体内和函数外部都可见。全局变量使用 global 关键字声明。
1
2
3
4
5
6
7
8
9
|
$global_var = 10;
function changeGlobalVariable() {
global $global_var ;
$global_var = $global_var + 1;
}
changeGlobalVariable();
echo $global_var ;
|
3. 静态变量
在函数中使用 static 关键字声明,它在每次函数调用之间保持其值。即使函数退出并重新调用,静态变量的值也不会丢失。
1
2
3
4
5
6
7
8
|
function incrementStaticVariable() {
static $static_var = 0;
$static_var ++;
return $static_var ;
}
echo incrementStaticVariable();
echo incrementStaticVariable();
|
实战案例:
以下示例演示了不同作用域的变量如何在 PHP 中使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
function testScope() {
$local_var = "Local Value" ;
global $global_var ;
$global_var = "Global Value" ;
static $static_var = "Static Value" ;
echo "Local Variable: $local_var<br>" ;
echo "Global Variable: $global_var<br>" ;
echo "Static Variable: $static_var<br>" ;
}
testScope();
echo "<br>" ;
testScope();
|
输出:
1
2
3
4
5
6
7
|
Local Variable: Local Value
Global Variable: Global Value
Static Variable: Static Value
Local Variable: Local Value
Global Variable: Global Value
Static Variable: Static Value 2
|