本文介绍了我可以将所有php全局变量放入函数的本地作用域吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在函数外部使用变量,我必须这样做:

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

函数Sum()
{
global $ a,$ b;

$ b = $ a + $ b;
}

Sum();
echo $ b;
?>

如果有很多全局变量,我只希望它们全部在本地范围内功能?我如何在每个函数开始时不保留一长串全局声明的情况下做到这一点?我不关心最佳做法或所有可能被认为是危险的原因。

理想情况下 ($ a $ b $ {

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b返回$ a + $ b;



$ b $ p
$ b

如果你真的无法避免引用函数范围之外的变量,那么你有几种选择:

使用$ GLOBALS数组:

 

函数Sum(){
return $ GLOBALS ['a'] + $ GLOBALS ['b'];

使用全局
$ p $ 函数Sum()
global $ a,$ b; $ c $关键字:


返回$ a + $ b;
}

使用并注入全局变量



<$ ($ a,$ b){
return $ a + $ b; pre $
}

$ result = $ Sum();

如果您想使用函数声明的范围内的变量来处理匿名函数, em>不是全球。



它们来自 $ GLOBALS

 函数Sum(){
extract($ GLOBALS);
返回$ a + $ b;



$ b

最后一个选项将拉入全部全局变量,并且看起来就是你要找的东西。



但是认真的,尽可能地参数化。


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.

解决方案

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.

这篇关于我可以将所有php全局变量放入函数的本地作用域吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:32