PHP教程
PHP Mysql
PHP面向对象
PHP常用

PHP 变量范围

PHP 变量范围

变量的范围定义为其在程序中可以访问的范围。换句话说,"变量的作用域是程序中定义并可以访问它的部分。"
PHP 具有三种类型的变量作用域:
局部变量 全局变量 静态变量

局部变量

在函数内声明的变量称为该函数的局部变量。这些局部变量仅在声明它们的特定函数中具有其作用域。这意味着不能在函数外访问这些变量,因为它们具有局部作用域。
函数外的同名变量声明与函数内声明的变量完全不同。让我们通过一个例子来理解局部变量:
文件: local_variable1.php
<?php
	function local_var()
	{
		$num = 45;	//local variable
		echo "Local variable declared inside the function is: ". $num;
	}
	local_var();
?>
输出:
Local variable declared inside the function is: 45
文件: local_variable2.php
<?php
	function mytest()
	{
		$lang = "PHP";
		echo "Web development language: " .$lang;
	}
	mytest();
	//using $lang (local variable) outside the function will generate an error
	echo $lang;
?>
输出:
Web development language: PHP
Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28

全局变量

全局变量是在函数外声明的变量。这些变量可以在程序的任何地方访问。要访问函数内的全局变量,请在变量前使用 GLOBAL 关键字。但是,这些变量可以在函数外直接访问或使用,无需任何关键字。因此不需要使用任何关键字来访问函数外的全局变量。
让我们通过一个例子来理解全局变量:

例子:

文件: global_variable1.php
<?php
	$name = "Sanaya Sharma";		//Global Variable
	function global_var()
	{
		global $name;
		echo "Variable inside the function: ". $name;
		echo "</br>";
	}
	global_var();
	echo "Variable outside the function: ". $name;
?>
输出:
Variable inside the function: Sanaya Sharma
Variable outside the function: Sanaya Sharma
注意: 在不使用 global 关键字的情况下,如果您尝试访问函数内部的全局变量,则会产生该变量未定义的错误。

示例:

文件: global_variable2.php
<?php
	$name = "Sanaya Sharma";		//global variable
	function global_var()
	{
		echo "Variable inside the function: ". $name;
		echo "</br>";
	}
	global_var();
?>
输出:
Notice: Undefined variable: name in D:\xampp\htdocs\program\p3.php on line 6
Variable inside the function:

使用 $GLOBALS 而不是全局

在函数内部使用全局变量的另一种方法是预定义 $GLOBALS 数组。
示例:
文件: global_variable3.php
<?php
	$num1 = 5;		//global variable
	$num2 = 13;		//global variable
	function global_var()
	{
			$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
			echo "Sum of global variables is: " .$sum;
	}
	global_var();
?>
输出:
Sum of global variables is: 18
如果local和global这两个变量同名,那么在函数内部,局部变量的优先级高于全局变量。
示例:
文件: global_variable2.php
<?php
	$x = 5;
	function mytest()
	{
		$x = 7;
		echo "value of x: " .$x;
	}
	mytest();
?>
输出:
Value of x: 7
注意: 局部变量的优先级高于全局变量。

静态变量

PHP 的一个特性是删除变量,一旦它完成执行并释放内存。有时我们甚至需要在函数执行完成后存储一个变量。因此,变量作用域的另一个重要特征是静态变量。我们在变量前使用static关键字来定义一个变量,这个变量叫做静态变量。
静态变量只存在于局部函数中,但不自由程序执行后其内存离开作用域。借助示例来理解:

示例:

文件: static_variable.php
<?php
	function static_var()
	{
		static $num1 = 3;		//static variable
		$num2 = 6;			//Non-static variable
		//increment in non-static variable
		$num1++;
		//increment in static variable
		$num2++;
		echo "Static: " .$num1 ."</br>";
		echo "Non-static: " .$num2 ."</br>";
	}
	
//first function call
	static_var();
	//second function call
	static_var();
?>
输出:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
您必须注意到 $num1 在每次函数调用后都会定期递增,而 $num2 不会。这就是为什么因为 $num1 不是静态变量,所以它在每次函数调用执行后释放其内存。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4