Declare A Global Variable In PHP
Code snippet for how to Declare A Global Variable In PHP with sample and detail explanation
Understanding how to declare a global variable in PHP is crucial for any developer specializing in this server-side scripting language. This article will guide you step by step on how to accomplish this task.
Code snippet
To declare a global variable in PHP, you need to use the global
keyword. Here’s a basic example:
<?php
$x = 30; //A local variable
function sampleFunction() {
global $x; //Making $x a global variable
echo $x; //Will output 30
}
sampleFunction();
?>
Code Explanation
Looking at our code snippet, we start by declaring a local variable $x
on line 2 and assigning it the value 30
. By default, this would only be accessible within the same block of code. However, we want $x
to be available throughout our entire PHP script.
Between lines 4-8, we define a function called sampleFunction()
. Inside this function, we declare $x
as a global variable by proceeding it with the global
keyword. We’re telling PHP we want to use the global version of $x
, not a local one.
After the global $x;
line, we now have access to $x
and its value 30
anywhere within sampleFunction()
. The echo $x;
line will thus print 30
.
Lastly, we call sampleFunction();
on the final line which outputs the global variable $x
on the web page.
Making $x
global allows it to be accessed and manipulated anywhere in your PHP script, not just in the function where it was declared. Therefore, knowledge of declaring global variables gives you more flexibility in programming PHP.
Remember, it’s always essential to declare global variables inside functions if you’re going to use them in that function. PHP doesn’t automatically access global variables in local scopes, hence the need for the global
keyword.