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.

Listing 6.5 creates a variable within a function and then attempts to print it outside the function.

Listing 6.5. Variable Scope: A Variable Declared Within a Function Is Unavailable Outside the Function
 1: <html> 2: <head> 3: <title>Listing 6.5</title> 4: </head> 5: <body> 6: <?php 7: function test() { 8: $testvariable = "this is a test variable"; 9: } 10: echo "test variable: $testvariable<br>"; 11: ?> 12: ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.