php中global的使用

起初,我是用sina微博写自己在用php时的一些收获。后来,我朋友说:作为一个程序员,用博客园写博客显得专业些。但是现在还是觉得用sina顺手些。好了,不废话了。

       变量分为全局变量和局部变量。学过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();

?>

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

php中global的使用

<?php

 

    $str = "string";

    function test()
    {  

       global $str;//上面的test函数中没有这句话

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

?>

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

php中global的使用

posted @ 2016-12-24 22:36  天涯海角路  阅读(159)  评论(0)    收藏  举报