Friday, May 13, 2016

Variable Scope

A variable declared within a function remains local to that function. In other words, it will not be available outside the function or within other functions. In larger projects, this can save you from accidentally overwriting the contents of a variable when you declare two variables with the same name in separate functions.

Create a variable within a function and then attempts to print it outside the function:
<?php
 function test() {
      $testvariable = "this is a test variable";
 }
 echo "test variable: ".$testvariable."<br/>";
 ?>
Put these lines into a text file called scopetest.php and place this file in your web server document root. When you access this script through your web browser, it should look like 




By the Way
The exact output you see depends on your PHP error settings. That is, it may or may not produce a "notice" as shown, but it will show the lack of an additional string after "test variable".
The value of the variable $testvariable is not printed because no such variable exists outside the test() function. Remember that the attempt in line 5 to access a nonexistent variable produces a notice such as the one displayed only if your PHP settings are set to display all errors, notices, and warnings; if your error settings are not strictly set, only the string "test variable" will be shown.
Similarly, a variable declared outside a function will not automatically be available within it.