Use of global keyword in php

怪我咯
Release: 2023-03-10 20:34:01
Original
1518 people have browsed it

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();

?>
Copy after login

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();
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template