Henry Cho
Henry Cho

Reputation: 770

php function no longer recognizes variable defined outside of it

i am relatively new to php and i've encountered a very strange problem. let me just give an example of a really simple code

$test = 'test';

function test(){
    echo $test;
}

test();

in the above example, it used to work just perfectly fine, returning 'test' as a result of calling the test() function. however, just today it started to return error saying the variable $test is undefined. i am 100 percent sure it worked just fine before. is this some update in php? or am i doing something wrong here? i am using wamp and testing this on my localhost. thanks!

Upvotes: 0

Views: 434

Answers (3)

Nanne
Nanne

Reputation: 64409

This is expected behaviour, it's called "variable scope"

read this: http://php.net/manual/en/language.variables.scope.php

One of the 'pitfalls' is:

You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

Upvotes: 4

Krista K
Krista K

Reputation: 21851

Inside the function, you need to declare global $test; for the variable test within the function test to have meaning. Further, any variables declared within curly braces {} will be unset upon leaving the scope of braces, not just within functions.

Upvotes: 2

deej
deej

Reputation: 2564

It is because it is outside the scope of function. To access variable defined outside function you must use global keyword.

$test = 'test';

function test(){
    global $test
    echo $test;
}

test();

Please read about variable scope on php manual link here: http://php.net/manual/en/language.variables.scope.php

Upvotes: 3

Related Questions