在程序中,变量用于存储一些值或数据,这些值或数据可以在程序中后续使用。变量也可以看作是容器,用于存储字符值、数值、内存地址和字符串。PHP有自己的变量声明和存储方式。
在处理PHP中的变量时,需要遵循一些规则和注意事项:
PHP用于声明或构造变量的数据类型有:
示例
<?php
// These are all valid declarations
$val = 5;
$val2 = 2;
$x_Y = "gfg";
$_X = "GeeksforGeeks";
// This is an invalid declaration as it
// begins with a number
$10_ val = 56;
// This is also invalid as it contains
// special character other than _
$f.d = "num";
?>
变量作用域
变量的作用域是指在程序中可以访问变量的范围,即变量的作用域是程序中可见或可以访问的部分。
根据作用域,PHP有三种变量作用域:
局部变量:在函数内部声明的变量称为该函数的局部变量,并且仅在该特定函数中具有作用域。简单来说,它无法在该函数之外被访问。在函数外部声明与函数内部同名的变量是完全不同的变量。我们将在后面的文章中详细了解函数。现在,可以将函数视为一组语句。
<?php
$num = 60;
function local_var()
{
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num \n";
}
local_var();
// $num outside function local_var() is a
// completely different Variable than that of
// inside local_var()
echo "Variable num outside local_var() is $num \n";
?>
输出:
local num = 50
Variable num outside local_var() is 60
全局变量:在函数外部声明的变量称为全局变量。这些变量可以在函数外部直接访问。要在函数内部访问这些变量,需要在变量之前使用“global”关键字来引用全局变量。
<?php
$num = 20;
// function to demonstrate use of global variable
function global_var()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
输出:
Variable num inside function : 20
Variable num outside function : 20
静态变量:PHP的特点是在执行完毕并释放内存后删除变量。但有时我们需要在函数执行完成后仍然存储变量。为了实现这一点,我们使用static关键字,这时的变量被称为静态变量。PHP根据变量的值关联一个数据类型。
示例:
<?php
// function to demonstrate static variables
function static_var()
{
// static variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// first function call
static_var();
// second function call
static_var();
?>
输出:
6
3
7
3
您可能已经注意到,即使在第一次函数调用后,$num仍然会定期递增,但$sum不会。这是因为$sum不是静态变量,在第一次函数调用执行后,其内存会被释放。
可变变量:
PHP允许我们使用动态变量名,称为可变变量。
可变变量实际上就是变量,其名称是由另一个变量的值动态创建的。
示例:
<?php
$a = 'hello'; //hello is value of variable $a
$$a = 'World'; //$($a) is equals to $(hello)
echo $hello; //$hello is World i.e. $hello is new variable with value 'World'
?>
输出:
World