Home  >  Article  >  Backend Development  >  Use of global keyword in php

Use of global keyword in php

怪我咯
怪我咯Original
2017-06-19 16:20:131519browse

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:

Use of global keyword in php

<?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:

Use of global keyword in php

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!

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