0

I executed following code but php says:

Notice: Undefined variable: b in ..\..\..\demo.php on line 4 
Notice: Undefined variable: a in ..\..\..\demo.php on line 4

Php Code:

<?php
  $a='a';$b='b';
  function test(){
      echo $a.$b;
  }
  test(); // error
?>

But i changed the code to this:

<?php
  $a='a';$b='b';
  function test($a,$b){
      echo $a.$b;
  }
  test($a,$b); // ab
?>

Why $a and $b are undefined in first case, since i defined them before? Why parameters need to pass in php? It's not require in other like JavaScript.

2
  • Add global $a, $b; in your first function and it will work :) Commented Mar 1, 2013 at 19:34
  • PHP and Javascript doe not follow the same scoping rules. See php.net/manual/en/language.variables.scope.php Commented Mar 1, 2013 at 19:38

3 Answers 3

2

If variables are defined outside the function, you need to specify the global keyword. Such as:

<?php
$a='a';$b='b';
function test(){
    global $a, $b;
    echo $a.$b;
}
test(); // error
?>

But your second example is the recommended way of handling it, typically.

Sign up to request clarification or add additional context in comments.

Comments

1

$a and $b in the first example you provided are attempting to access those variables respectively from the local scope not the global scope. You could try declaring them like this

 function test() {
     global $a, $b;
     echo $a . $b; //or $GLOBALS['a'].$GLOBALS['b'];
 }

and you will get the correct values.

Comments

0

Try this

$a = '101';
$func = function() use($a) {
    echo $a;
};

function func_2() {
    global $func;
    $a = 'not previouse a';
    $func();
}

func_2();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.