0

I am surprised to see that the global variable does not need any initialization before it can be used in the program. Here's my small snippet which forced me to ask this question:

<?php
function set_variable()
{
    global $name;
    //$name = "admin";
}

set_variable();
?>

<input type="text" name="name" value="<?php echo $name; ?>" />

When this code is executed, it all works well. But if I don't make my variable name as global then I see Undefined variable: name in the textbox. Why does global make a huge difference?

Sachin
  • 1,646
  • 3
  • 22
  • 59
  • 2
    `global $name;` behaves like `$name = & $GLOBALS["name"];` and thus implicitly creates it (with `NULL` as initial value). – mario Sep 09 '18 at 15:14
  • Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – castis Sep 09 '18 at 15:22
  • @mario yes you exactly talked about the point what I was asking. – Sachin Sep 09 '18 at 18:05

1 Answers1

0

If a variable is declared outside the function its already in global scope. So there is no need to declare the variable as global.But if you are calling from inside the function you have to use global keyword.Those variable are not accessible inside function unless you declare them with global.

Mani Ratna
  • 883
  • 1
  • 11
  • 30