Home > Article > Backend Development > Use of global keyword in php
Amounts are divided into global variables and local variables. Children who have learned C language all know that the scope of global variables is the entire file. It is valid even inside function, but in PHP, if you use a global variable in a function, PHP will think that this variable is not defined. If we need to use this global variable inside the function, then we need to add the keyword global before the global variable inside the function. Below is a small demo I wrote. To prove what I said above
<?php $str = "string"; function test() { if (isset($str)) { echo "the string is defined"; } else { echo "the string is undefined"; } } test(); ?>
This is the result of running in the browser:
<?php $str = "string"; function test() { global $str;//上面的test函数中没有这句话 if (isset($str)) { echo "the string is defined"; } else { echo "the string is undefined"; } } test(); ?>
This is the result of running in the browser:
The above is the detailed content of Use of global keyword in php. For more information, please follow other related articles on the PHP Chinese website!