dprnr5559 2014-08-07 16:37
浏览 44
已采纳

我可以将所有php全局变量拉入函数的本地范围吗?

In order to use variables outside of a function, I have to do this:

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b;
?>

What if there are a lot of global variables, and I just want them all to be locally scoped inside the function? How do I do this without maintaining a long list of global declarations at the beginning of each function? I'm not concerned about best practices, or all the reasons it may be considered dangerous.

  • 写回答

2条回答 默认 最新

  • dqwr32867 2014-08-07 17:01
    关注

    Ideally, everything your function needs should be in a parameter.

    function Sum($a, $b) {
      return $a + $b;
    }
    

    If you really can't avoid referring to variables outside your function scope, you have several options:

    Use the $GLOBALS array:

    function Sum() {
      return $GLOBALS['a'] + $GLOBALS['b'];
    }
    

    Use the global keyword:

    function Sum()
      global $a, $b;
      return $a + $b;
    }
    

    Use an "anonymous" function and inject the globals

    $Sum = function() use ($a, $b) {
      return $a + $b;
    }
    
    $result = $Sum();
    

    Anonymous functions are more useful if you want to work with variables in-scope of the functional declaration that aren't global.

    extract() them from $GLOBALS

    function Sum() {
      extract($GLOBALS);
      return $a + $b;
    }
    

    This last option will pull in all globals, and seems to be what you're looking for.

    But seriously, parametize whenever possible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误