3.7. Variables and Scope

Variables cannot be “seen” in the entire application. This is a very important issue because otherwise programmers would easily run into trouble. Especially when building huge applications, it is important to know where which variables can be seen and used.

Let's start with a simple example:

<?php
        $a = "Hello World";
        echo "main: $a<br>\n";
        display_data();

function display_data()
{
        echo "display data: $a<br>\n";
}
?>

First, $a is initialized and displayed on the screen. Then display_data is called, which tries to display $a again:

main: Hello World
display data:

As you can see, display_data displays nothing because $a cannot be seen by the function. $a has been initialized in the main function and therefore it is not ...

Get PHP and PostgreSQL: Advanced Web Programming 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.