php中global的使用

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

这是在浏览器中的运行结果:
the string is undefined

<?php

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

这是在浏览器中的运行结果:
the string is defined


$GLOBALS — 引用全局作用域中可用的全部变量

一个包含了全部变量的全局组合数组。变量的名字就是数组的键。

<?php
function test() {
    $foo = "local variable";

    echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
    echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>

以上例程的输出类似于:

$foo in global scope: Example content
$foo in current scope: local variable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值