Home > Article > Backend Development > The four major scopes of PHP variables
PHP variable scope
● local
● global
● static
● parameter
Local scope, global scope
<?php $x = 50; // 全局变量 function myTest() { $y = 100; // 局部变量 }
PHP global keyword
The global keyword is used to access global variables within a function.
To call global variables defined outside the function within a function, you can add the global keyword before the variables in the function.
<?php $x = 50; $y = 100; function myTest() { global $x, $y; $y = $x + $y; } myTest(); echo $y; // 输出 150
PHP stores all global variables in an array called $GLOBALS.
So the above code can be written in another way:
<?php $x = 50; $y = 100; function myTest() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } myTest(); echo $y;
PHP Static scope
PHP When a function completes, all its variables are usually will be deleted. In order to prevent some local variables from being deleted, you can use the static keyword when declaring the variable for the first time.
<?php function myTest() { static $x = 0; echo $x; $x++; echo PHP_EOL; } myTest(); myTest(); myTest();
Parameter scope (formal parameter)
Parameter declaration as part of the function declaration.
<?php function myTest($x) { echo $x; } myTest('Galois'); myTest(8888);
Small addition:
Print array method:
echo '<pre class="brush:php;toolbar:false">'; print_r($arr);
Related recommendations:php tutorial
The above is the detailed content of The four major scopes of PHP variables. For more information, please follow other related articles on the PHP Chinese website!