PHP:从函数内部声明具有全局作用域的变量[复制]

时间:2022-10-08 00:41:19

Possible Duplicate:
Declaring a global variable inside a function

可能重复:在函数内声明全局变量

Is it possible to declare variable with global scope from inside a function?

是否可以从函数内部声明具有全局范围的变量?

NOTE: I don't want to receive the value of a previously declared variable outside the function. But to have the values of the variables declared inside the function working outside the function scope.

注意:我不希望在函数外部接收先前声明的变量的值。但要使函数内部声明的变量值在函数作用域之外工作。

I a way that if I have these variables declared inside a function:

我有一种方法,如果我在函数内声明了这些变量:

function variables($n){
    $a=1+$n;
    $b="This is number +$n";
}

I could echo them outside the function:

我可以在函数之外回应它们:

variables(1);
echo $a;
echo '\n';
echo $b;

2
This is number 1

I know I could achieve it returning an array from the function but... I'd like to be sure I could otherwise.

我知道我可以实现它从函数返回一个数组但是...我想确定我可以。

I saw nothing here: http://php.net/manual/en/language.variables.scope.php

我在这里什么都没看到:http://php.net/manual/en/language.variables.scope.php

Thanks.

1 个解决方案

#1


4  

You can read elsewhere about why globals are bad, so I'll just stick to the question. You can use the global keyword for this. The same applies if you want to read a global from inside a function.

你可以在其他地方读到有关为什么全局变坏的原因,所以我只会坚持这个问题。您可以使用global关键字。如果要从函数内部读取全局,则同样适用。

function variables($n){
    global $a,$b;
    $a=1+$n;
    $b="This is number +$n";
}

#1


4  

You can read elsewhere about why globals are bad, so I'll just stick to the question. You can use the global keyword for this. The same applies if you want to read a global from inside a function.

你可以在其他地方读到有关为什么全局变坏的原因,所以我只会坚持这个问题。您可以使用global关键字。如果要从函数内部读取全局,则同样适用。

function variables($n){
    global $a,$b;
    $a=1+$n;
    $b="This is number +$n";
}