0

Code below prints produces error:

Notice: Undefined variable: x in C:\wamp\www\h4.php on line 9

and output:

Variable x inside function is:
Variable x outside function is: 5

Code:

<html>
<body>

<?php
$x = 5; // global scope

function myTest() {
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";
} 
myTest();

echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html>

What gets wrong with x global variable inside of myTest function?

vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

2

Change to this:

function myTest() {
    global $x;
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";
} 

The global command says to use the global value of $x rather than a private one.

Chris Lear
  • 6,592
  • 1
  • 18
  • 26
2

To access global variable you need to define with 'global' keyword with in the function.After define it you can access that global variable.

      $x = 5; // global scope

        function myTest() {
//use global keyword to access global variable
            global $x;
            // using x inside this function will generate an error
            echo "<p>Variable x inside function is: $x</p>";
        } 
        myTest();

    echo "<p>Variable x outside function is: $x</p>";
Domain
  • 11,562
  • 3
  • 23
  • 44