PHP如何使用变量?全局变量和局部变量怎么用?

2021年4月2日12:27:00 发表评论 840 次浏览

变量

程序中的变量用于存储某些值或数据, 以便以后在程序中使用。 PHP有自己的声明和存储变量的方法。

处理PHP中的变量时, 需要遵循的规则很少, 并且要记住一些事实:

  • PHP中声明的所有变量都必须以美元符号($), 然后是变量名。
  • 变量可以具有长描述性名称(例如$ factorial, $ even_nos)或短名称(例如$ n或$ f或$ x)
  • 变量名称中只能包含字母数字字符和下划线(即" a-z", " A-Z", " 0-9和" _")。
  • 变量的分配是通过赋值运算符"等于(=)"完成的。变量名在等号的左边, 表达式或值在赋值运算符" ="的右边。
  • 必须记住, PHP名称中的变量名称必须以字母或下划线开头, 且不能为数字。
  • PHP是一种松散类型的语言, 我们不需要声明变量的数据类型, 而是PHP通过分析值自动假定它。转换时也会发生同样的情况。
  • PHP变量区分大小写, 即$ sum和$ SUM被区别对待。

例子:

<?php
  
// These are all valid declarations
$val = 5;
$val2 = 2;
$x_Y = "gfg" ;
$_X = "lsbin" ;
  
// 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
  
// 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不是静态的, 并且在执行第一个函数调用后释放了其内存。

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: