Читать книгу PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO) - Sergey D Skudaev - Страница 7

Variable Scope

Оглавление

Variables in the PHP code may have different scopes. They may be seen or accessed globally, anywhere on the current php page or only inside the function. Let us analyze the following code:


<?php


$greeting=“Hello!”;


function greetme ($name) {


echo $greeting.””. $name;

}


//function call

greetme (“John’);

?>


Output: John


At the beginning of the code, we assigned the “Hello” string to the $greeting variable. Then we defined the function with one parameter $name. Inside the function we concatenated the $name variable to the $greeting variable. Then we called the function and passed the name “John’ as a parameter.

You might expect the Output: would be “Hello John”, since $greeting equals “Hello”, but it’s “John”. “Hello” is not visible because the $greeting variable inside the function is not the same as outside. It’s local, and because we assigned no value to the local variable $greeting, the value we passed as a parameter is the only one visible.

Let us modify the function.


<?php


$greeting=“Good morning!”;


function greetme ($name) {


$greeting=“Hi There”;


echo $greeting.””. $name;


}


echo greetme (“John’);

echo "<br>”;

echo “Greeting=”. $greeting.”<br>”;


?>


Output:

Hi There John

Greeting=Good Morning


Inside the function we assigned the value “Hi There” to the local variable $greeting. As a result, the function will return “Hi There John”. However, because we printed the $greeting variable outside the function, the global variable $greeting value remains “Good Morning”.

Let us modify our code again.


<?php


$greeting=“Good Morning”;


function greetme ($name) {


global $greeting=“Hi There”;


echo $greeting.””. $name;


}


echo greetme (“John’);


echo "<br>”;


echo “Greeting=”. $greeting.”<br>”;


?>


Output:

Hi There John

Greeting=Hi There


In the above we’ve declared a global variable inside the function, using global. Then we assigned the value “Hi There” to the global $greeting variable.

We previously assigned “Good Morning” to the global variable $greeting outside the function. Then, inside the function, we assigned a global variable with the same name to the value “Hi There”. Now the global variable $greeting no longer has the value “Good Morning”, but rather “Hi There”. So, when we print the value of the global variable outside the function it displays, “Hi There”.

PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO)

Подняться наверх