php 中global关键字的使用

怪我咯
怪我咯 原创
2023-03-10 20:34:01 1047浏览

量分为全局变量和局部变量。学过C语言的童鞋都知道,全局变量的作用域是整个整个文件。在即使在函数内部也有效,但在php中,如果在函数中使用全局变量,php会认为这个变量没有定义。如果我们需要在函数内部使用这个全局变量,这时我们就需要在函数内部,这个全局变量前加关键字global。下面是自己写的一个小demo。用来证明我上面说的

<?php

 

    $str = "string";

    function test()
    {  

       if (isset($str)) 
       {
          echo "the string is defined";
       }
       else 
       {
          echo "the string is undefined";
       }
    }
    test();

?>

这是在浏览器中的运行结果:

8eebfeb0gb6a48ec23070&690.jpg

<?php
 
    $str = "string";
    function test()
    {  
       global $str;//上面的test函数中没有这句话
       if (isset($str)) 
       {
          echo "the string is defined";
       }
       else 
       {
          echo "the string is undefined";
       }
    }
    test();
?>

这是在浏览器中的运行结果:

8eebfeb0gb6a4a32d9abf&690.jpg

以上就是php 中global关键字的使用 的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。