Why the output is not displayed with a new variable?

Viewed 43

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 

?>
2 Answers

$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();

You should use variable $h as global variable

$x = 5 . "*";
$y = 10 . "=";
$h = null;// declare $h
function myTest() {
  global $x, $y, $h; //use $h here
  $h = $x + $y; //new variable
} 
myTest();  // run function

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