Home  >  Article  >  Backend Development  >  PHP variables

PHP variables

WBOY
WBOYOriginal
2016-07-29 08:58:181136browse

  • Variables are "containers" used to store information:
$x=5;
$y=6;
$z=$x+$y;
echo$z;
?>

Variables are containers used to store data.

  • PHP variables

Similar to algebra, you can assign a certain value (x=5) or expression (z=x+y) to a PHP variable.
Variables can have very short names (such as x and y) or more descriptive names (such as age, carname, totalvolume).
PHP variable rules:
The variable is opened with the symbol Start , afterfacefollowed by withchange amount of nameweighing changeamount namemustmust with the words Mother or or Drawline word Talismanopen StartChange QuantityNameOnlycan PackContains wordsmothercount word word Talisman with and drawline (A?z0?9 and )changeamount NameNo CanPackContainsEmpty Grid Changeamountname is DistrictPoints bigsmallwrite ( y and $Y are two different variables) lamp PHP statements and PHP variables are case-sensitive.

  • PHP 是一门弱类型语言

在上面的实例中,我们注意到,不必向 PHP 声明该变量的数据类型。
PHP 会根据变量的值,自动把变量转换为正确的数据类型。
在强类型的编程语言中,我们必须在使用变量前先声明(定义)变量的类型和名称。

  • 局部和全局作用域

在所有函数外部定义的变量,拥有全局作用域。除了函数外,全局变量可以被脚本中的任何部分访问,要在一个函数中访问一个全局变量,需要使用 global 关键字。
在 PHP 函数内部声明的变量是局部变量,仅能在函数内部访问:

你可以在不同函数中使用相同的变量名称,因为这些函数内定义的变量名是局部变量,只作用于该函数内

  • PHP global 关键字

global 关键字用于函数内访问全局变量。
在函数内调用函数外定义的全局变量,我们需要在函数中的变量前加上 global 关键字:
实例

$x=5;
$y=10;

functionmyTest()
{global$x,$y;
$y=$x+$y;
}

myTest();
echo$y; // 输出 15?>

PHP 将所有全局变量存储在一个名为 $GLOBALS[index] 的数组中。
index 保存变量的名称。
这个数组可以在函数内部访问,也可以直接用来更新全局变量。
上面的实例可以写成这样:
实例

$x=5;
$y=10;

functionmyTest()
{$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
} 

myTest();
echo$y;
?>
  • Static 作用域

当一个函数完成时,它的所有变量通常都会被删除。然而,有时候您希望某个局部变量不要被删除。
要做到这一点,请在您第一次声明变量时使用 static 关键字:
实例

functionmyTest()
{static$x=0;
echo$x;
$x++;
}

myTest();
myTest();
myTest();

?>

然后,每次调用该函数时,该变量将会保留着函数前一次被调用时的值。
注释:该变量仍然是函数的局部变量。

  • 参数作用域

参数是通过调用代码将值传递给函数的局部变量。
参数是在参数列表中声明的,作为函数声明的一部分:
实例

functionmyTest($x)
{echo$x;
}
myTest(5);
?>

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了PHP 变量,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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