开发者

PHP: declare variable with global scope from inside a function [duplicate]

开发者 https://www.devze.com 2023-04-13 06:00 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Declaring a global variable inside a function
This question already has answers here: Closed 11 years ago.

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 returnin开发者_开发技巧g 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

Thanks.


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.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号