PHP全局或$ GLOBALS [英] PHP global or $GLOBALS

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

问题描述


  1. 是否有一个最佳实践/建议,当我想要使用在函数外部声明的变量时: 全球$ myVar

  2. $ GLOBALS ['myVar']

谢谢。

解决方案

应该真的是将变量传递给函数,而不是使用全局。



一个示例,如何通过将函数作为参考参数传递给函数以外的变量:

  function myFunc(& $ myVar)
{
$ myVar = 10;
}

$ foo = 0;
myFunc($ foo);
var_dump($ foo); //产生10


Is there a best practice / recommendation when I want to use a variable declared outside of a function when it comes to using:

  1. global $myVar
  2. $GLOBALS['myVar']

Thank you.

解决方案

What you should really do is pass the variable to the function instead of using a global at all.

An example how to change a variable outside of the function via passing it as reference parameter:

function myFunc(&$myVar)
{
    $myVar = 10;
}

$foo = 0;
myFunc($foo);
var_dump($foo); // yields 10

这篇关于PHP全局或$ GLOBALS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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