This article mainly introduces the scope, global, static and other keywords of PHP variables. It has certain reference value. Now I share it with you. Friends in need can refer to it
Local and global scope
Variables defined in the function body in php are local variables, and variables defined outside the function are called global variables
<?php $x=5; // 全局变量function myTest() { $y=10; // 局部变量 echo "<p>测试函数内变量:<p>"; echo "变量 x 为: $x"; echo "<br>"; echo "变量 y 为: $y"; } myTest(); echo "<p>测试函数外变量:<p>"; echo "变量 x 为: $x"; echo "<br>"; echo "变量 y 为: $y";?>
2 . global keyword
Global variables cannot be used in the function body in php. If you want to use them, you need to use the global keyword to declare them before use
<?php $x=5; $y=10; function myTest() { global $x,$y; $y=$x+$y; } myTest(); echo $y; // 输出 15?>
3.static scope
When the function finishes running, the variables within the function will be eliminated. If you still need to use them and do not want them to be deleted, use the static keyword. Only used when declaring a variable for the first time.
<?php function myTest() { static $x=0; echo $x; $x++; } myTest(); myTest(); myTest();?>
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Commonly used array functions in PHP
Introduction to static variables in PHP
The above is the detailed content of PHP variable scope, global, static and other keywords. For more information, please follow other related articles on the PHP Chinese website!