Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

php - Global variables aren't working as expected with frameworks

I'm trying to use global variables in my php script, and I found the usage of global variable on php.net. But it doesn't work on my local server. Is there any configuration I have missed out?

There is an example found on that page:

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

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

    $b = $a + $b;
} 

Sum();
echo $b;
?>

The above script will output 3.

However my output is 2!

Another example:

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

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

Sum();
echo $b;
?>

I get error:

Undefined index: a

So what is the deal with that? Why doesn't my code work as expected?
By they way, I'm using Laravel.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So as I guessed you are using a framework as you said in the comments:

@Rizier123 Yes, I'm using Laravel. Does it matter? – Kai 6 mins ago

And if it matters? Yes it does.

Probably what is happening here is, that the code which you show us here is wrapped into another function somewhere else.

Means that the variables in the Sum() function are in global scope, but the other ones outside of it not, since they are probably in another function == another scope.


You can reproduce it with this code:

function anotherFunction() {
    $a = 1;
    $b = 2;

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

    Sum();
    echo $b;
}

anotherFunction();

And if you have error reporting on you will get:

Notice: Undefined index: a
Notice: Undefined index: b
2

Just put the error reporting at the top of your file(s) to get useful error messages:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
?>

To solve this now you have to declare the variables also in global scope, either with:

$GLOBALS["a"] = 1;
$GLOBALS["b"] = 2;

or like this:

global $a, $b;
$a = 1;
$b = 2;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...