Search code examples
phpfunctionechoglobal

Why the output is not displayed with a new variable?


Why output ($h) not displayed? I don't want to delete (function)

please correct it.

Here is my code:

<?php
$x = 5 . "*";
$y = 10 . "=";

function myTest() {
    global $x, $y;
    $h = $x + $y; //new variable
} 
myTest();  // run function

echo $x . $y . $h; // output the value 

?>

Solution

  • $h only has scope inside the test function. To get the $h value, you could either make $h global, or preferably return the value from the myTest function.

    Note: the function should normally be a self-contained unit. By giving globals scope inside the function (using global $x, $y) introduces un-needed and possibly harmful dependencies to code. The code below is an example only to illustrate the solution to your question.

    function myTest() {
        global $x, $y;
        return $x + $y;
    } 
    
    $h = myTest();