There’s a thing called scope in programming. This refers to where in your scripts a variable can be seen. If a variable can bee seen from anywhere, it’s said to have global scope. In PHP, variables inside of functions can’t be seen from outside of the function. And functions can’t see variables if they are not part of the function itself. Try this variation of our script as an example:

<?PHP

$error_text = "Error Detetceted";

display_error_message();

function display_error_message( ) {

print $error_text;

}

?>

This time, we have set up a variable called $error_text to hold the text of our error message. This is set up outside of the function. Run the script, and you’ll get a PHP error message about ” Undefined variable”.

Likewise, try this script:

<?PHP

display_error_message();

print $error_text;

function display_error_message() {

$error_text = "Error message";

}

?>

This time, the variable is inside the function, but we’re trying to print it from outside the function. You still get an error message. Here’s a correct version:

<?PHP

display_error_message();

function display_error_message() {

$error_text = "Error message";
print $error_text;

}

?>

 

Here, we have both the variable and the print statement set up inside of the function. The error message now prints.