声明一个全局数组 [英] Declaring a global array

查看:130
本文介绍了声明一个全局数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.我最近学习了PHP,并试图声明一个全局数组,以便可以在函数内部进行访问.但是我似乎缺少了一些东西,因为我得到了错误未定义的变量:"

Hi. I recently learned PHP and am trying to declare a global array so I can access inside a function. But I seem to be missing something because I get the error 'Undefined variable:'

这是我的代码:

global $second_array;
$second_array = array();

function operatii($v) {
  $var1 = $second_array[count($second_array)-1];
  $var2 = $second_array[count($second_array)-2];
  $rez = null;

  echo $var1 . $var2 . "este?";
}

for ($i = 0; $i < count($a); $i++){
  if ($a[$i] === "+" || $a[$i] === "-" || $a[$i] === "*" || $a[$i] === "/" ) {
    operatii($a[$i]);
  } else {
    array_push($second_array, $a[$i]);
  }
}

我似乎能够在for循环中使用$second_array,但不能在操作函数中使用它.
我该如何解决这个问题?

I seem to be able to use the $second_array in the for loop, but can't use it in the operatii function.
How can I solve this problem?

推荐答案

在PHP中有两种引用全局变量的方法:

There are two ways to reference a global variable in PHP:

  1. 在每个使用该变量的函数的开头使用global关键字.
  2. 使用$GLOBALS数组.
  1. Use the global keyword at the start of every function that uses the variable.
  2. Use the $GLOBALS array.

在这些变量中,我建议坚持使用第二个变量,因为它始终使变量绝对是全局变量.

Of these, I recommend sticking with the second, since it makes it absolutely clear at all times that the variable is a global.

全局变量的问题之一是跟踪它们的使用位置.使用$GLOBALS数组可以在某种程度上缓解此问题.

One of the problems with globals is keeping track of where they're being used; using the $GLOBALS array mitigates this issue to some extent.

但是,使用全局变量仍然存在一些问题.通常,在您的代码中使用太多的全局变量被认为是一种不好的做法.在使用了许多广泛使用全局变量的遗留系统之后,我可以保证它们会为将来的开发人员带来很多麻烦.

However, there are still issues with using globals; it's generally considered poor practice to use too many globals in your code. Having worked with a number of legacy systems that used globals extensively, I can vouch for the fact that they can cause a lot of headaches for future developers.

使用全局变量也使为代码编写正式的测试套件(即单元测试)变得更加困难.

Using globals also makes it harder to write formal test suites for your code (ie unit tests).

因此,我的建议是尽可能避免使用全局变量.在某些情况下,它们是必需的,但是您越可以避免使用它们,而是将变量传递到您的函数和类中,而不是使其成为全局变量,效果会更好.

My recommendation would therefore be to avoid using globals at all where possible. They are necessary in some cases, but the more you can avoid them, and instead pass variables into your functions and classes rather than making them global, the better things will be.

总结一下:

如果必须使用全局变量,请使用$GLOBALS['varname']引用它们,但是通常最好不要使用它们.

If you must use globals, reference them with $GLOBALS['varname'], but it's usually better not to use them at all.

希望有帮助.

这篇关于声明一个全局数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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