php7是否仍然支持全局变量? [英] Does php7 still support global variables?

查看:90
本文介绍了php7是否仍然支持全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 php7 中的函数内使用全局变量?它在php5.4中正常工作.

It is possible to use global variable within function in php7? It worked properly in php5.4.

我发现关键字 global 在php7中不再有用:

I have found that keyword global is not usefull any more in php7:

global仅接受简单变量 migration70.incompatible

但是关于GLOBALS的页面上有 reserved.variables.globals 仍然有记载(PHP 4,PHP 5,PHP 7)应该支持GLOBALS.

But There on page about GLOBALS reserved.variables.globals it is still written that (PHP 4, PHP 5, PHP 7) should support GLOBALS.

不幸的是,这些都不对我有用:

Unfortunatelly, nothing of these work for me:

function printGlobal(){
  global ${$a};
  global $b;
  echo '<br/>-'.${$a};
  echo '<br/>-'.$b;
  echo '<br/>-'.$GLOBALS['c'];
}

$a = "hello";
$b = 7;
$c = 6;

printGlobal();

输出:

-
-
-

请不要开始有关避免使用全局变量的讨论:)

Please do not start a discussion about avoiding of usage of global variables :)

---

我错过了,我使用的X.php文件包含在函数includeAnotherPage(..)中的index.php文件中.因此,在X.php文件中定义的变量不能是全局变量-因为整个X.php文件已经在函数中.因此,上面编写的代码不起作用.

I missed, that X.php file I worked with is included withinin index.php file in a function includeAnotherPage(..). Thus, variable defined in X.php file cannot be global variable - because whole X.php file is already in a function. Therefore, codes, writen above, did not work.

好,谢谢您的答复.我很愚蠢,文章使我感到无法激活全局变量.

Ok thank you for replies. I am stupid and the article locked me in the feeling that globals could be deactivated.

推荐答案

PHP还为您提供了使用超级全局变量之一$GLOBALS定义全局变量的选项.因此,您可以执行以下操作,也可以在此处快速测试:

PHP also gives you the option of defining Global Variables using one of the Super-Globals: $GLOBALS. So you could do something like below which you might QUICK TEST Here as well:

<?php

    $GLOBALS['a']      = "hello";
    $GLOBALS['b']      = 7;
    $GLOBALS['c']      = 6;
    $GLOBALS['hello']  = "Howdy...";

    function printGlobal(){
      $a = $GLOBALS['a'];
      $b = $GLOBALS['b'];
      $c = $GLOBALS['c'];
      $d = $GLOBALS[$a];

      echo '<br/>-'.$d;
      echo '<br/>-'.$b;
      echo '<br/>-'.$c;
    }

    printGlobal();

这篇关于php7是否仍然支持全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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