Use Global Variable

The Global variable comes with a special characteristic. You can use them anywhere on the page having the php tag.

Here is the example.

[php]<?php
$x = 5; // global scope
function testbar() {
echo "<p>Variable x inside function is: $x</p>";
}
testbar();
echo "<p>Variable x outside function is: $x</p>";
?>[/php]

The above code has Global variable “$x” which has given value “5”. If I run the code I will get a result.

[php]Variable x inside function is:

Variable x outside function is: 5[/php]

You can see the php code ignored the first sentence and provided nothing to X value. On other hands, the second sentence got the value from the Global variable as it is mentioned after the curly bracket of the function code.

You can call this variable from anywhere without having separate function tag. You just need to put the basic php tag to get the global variable anywhere on the page.

for e.g.

[php]<?php
echo "<p>Variable x outside function is: $x</p>";
?>[/php]

The code can get the value of the “$x” from the Global variable. I can put this code anywhere on the same page where the global variable is available to get the value of X.

Related Posts

Leave a Reply