views:

121

answers:

3

This is a contrived example

function test()
{
    global $a;
    $a=2;
}

test();

//here $a will report undefined variable

echo $a;

I meet this problem now by somehow,but I can't reproduce it in an easy way!

EDIT

I mean operations like include or alike by when

A: 

One way for you getting the undefined variable at the place you've mentioned is when you make $a local to function test() by not having the global $a; declaration.

<?php
function test()
{
    //global $a;
    $a=2;
}

test();

//here $a will report undefined variable

echo $a;
?>

The other could be you are calling the function test() after the echo:

<?php
function test()
{
    global $a;
    $a=2;
}


//here $a will report undefined variable

echo $a;

test();
?>

The variable a has not been initialized when its being printed and will result in Notice: Undefined variable: a

The snippet you've provided should work just fine. At the point where you are echoing $a, its no more undefined and has been given a value in the function test().

codaddict
It's not the problem I met.There is `global` declaration and echo is after function call.
+1  A: 

You recently edited to say that is happens when you 'include' a file.

Files and Globaling don't really get along. You actually have to Global out and into a file. So if test1.php had this code

$a = 5;

and test2.php had this code:

$a = 3;

and test3.php had this code:

$a = 10;

and finally (Yes, too many files) testMaster.php had this code

include 'test1.php';
include 'test2.php';
include 'test3.php';
echo $a;

There would be an undefined variable error. You would have to go an individually global the variable in each file in order for them all to get set.

Now, I'm pretty sure this wouldn't affect the code you gave us, or if function test() was included, and then called test(); and right after it you put echo $a;. But if you define AND call test() in a separate file than you echo $a, it would cause a globaling error.

I'm not sure if this answers your question, but yes, this is a flaw in the include system.

Chacha102
It works fine here,output 10.
A: 

It can happen if you do this inside test():

unset($GLOBALS['a']);

I doubt you are though, maybe you can update your post to provide a code sample that better resembles your situation.

Kevin
No,I didn't do such silly thing.