2

I have a php file:

<?php
$a = 1;
function test(){ 
    echo $a;
} 
test();
?>

And I get this error:

Notice: Undefined variable: a in X:\...\test.php on line 4

Using XAMPP @ 32bit W7.

4
  • Its because of the function scope. you would need to write global $a; at the top of the function, but you should avoid global variables. Read a bit about scope in php Commented Sep 4, 2011 at 2:36
  • 2
    php.net/manual/en/language.variables.scope.php Commented Sep 4, 2011 at 2:37
  • PHP does not have real global variables. You need to chain to the shared scope if you want this to work. (Example too abstract. But it's frequently misused by newcomers; function parameters are usually the advisable approach.) Commented Sep 4, 2011 at 2:51
  • 1
    Also NARQ: Please formulate your posts as actual questions. Add more details and real code if you want case-specific help. See higher quality question and sample code howtos. Commented Sep 4, 2011 at 2:54

3 Answers 3

7

Variables have function scope. $a inside the function is not the same as $a outside the function. Inside the function you have not defined a variable $a, so it doesn't exist. Pass it into the function:

$a = 1;
function test($a) { 
    echo $a;
} 
test($a);
Sign up to request clarification or add additional context in comments.

Comments

1

You have trouble understanding variable scope. $a is defined in the global scope, but not in the function scope. If you want your function to know what $a contains, you have two choices :

  1. Make it global (usually a bad solution)
  2. Add a new argument to your function, and pass your variable to your function

Comments

1

You can use global as advised, but that is bad practice. If you need variables in a function from outside the function then pass them as parameters.

$a = 1;
function test($a) {
    echo $a;
}
test($a);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.