"GLOBAL"和"GLOBAL"之间有什么区别?和“静态" PHP中的变量? [英] What is the difference between "GLOBAL" and "STATIC" variable in PHP?

查看:84
本文介绍了"GLOBAL"和"GLOBAL"之间有什么区别?和“静态" PHP中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中GLOBAL和STATIC变量之间到底有什么区别?当我们要在多个函数中使用变量时,最好使用哪一个?

What exactly is the difference between the GLOBAL and STATIC variables in PHP? And which one is preferable to use, when we want to use a variable in multiple functions?

谢谢.

推荐答案

Global用于获取可以在其他脚本中定义或不在相同范围内的全局变量.

Global is used to get the global vars which may be defined in other scripts, or not in the same scope.

例如

<?php

$g_var = 1;

function test() {
   var_dump($GLOBAL['g_var']);

   global $g_var;
   var_dump($g_var);
} 

静态用于定义一个具有完整脚本寿命的var,并且只能初始化一次.

Static is used to define an var which has whole script life, and init only once.

例如

<?php

function test() {
    static $cnt = 0;
    $cnt ++;
    echo $cnt;
} 

$i = 10;

while (-- $i) {
    test();
}

这篇关于"GLOBAL"和"GLOBAL"之间有什么区别?和“静态" PHP中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆