How to Create a Global Variable in PHP



PHP


In this article, we show how to create a global variable in PHP.

A global variable is a variable that can be used in any part of a PHP program. The opposite of this is a lcoal variable, which is a variable that can only be used in a certain part of a program.

To create a global variable in PHP, all you have to do is put the keyword global in front of the variable.

So if we have a variable named $variable_name, to make this variable a global variable, you simply put global in front of the variable.



So if now the variable_name is a global and can be used in any part of our PHP program.

When would we want to make a variable global?

A perfect example may be in a function.

If a variable is declared and initialized in a function, it is a local variable. It can only be utilized in that function. If you try to get its value outside of the function, you will not be able to do so. It's only local to that function. Only through the function would you be able to access it.

However, if you declare that variable global within the function, then it can be used and accessed outside of the function.

Let's say we have the code shown below.



So we have a function called uservalue(). This function has a variable that has been set to the value of 2.

If we then try to access this function outside of this function in any way, we will not be able to do so. It's local only to the uservalue() function.

So when we echo out the value of the number, it will be a blank output. The $number variable cannot be accessed outside of the function.

However, if we make this variable, it can.

Below is the code making this variable global.



Now this code will produce 2 at the output for the $number variable.

This is because the $number variable is now global. It can be referenced now even outside of the function.

So this is just a quick tutorial on making a PHP variable global.

Related Resources

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from a Check box with PHP

How to Retrieve Data from an Array of Checkboxes with PHP

How to Retrieve Data from a Drop-down List with PHP

How to Retrieve Data from a List Box with PHP

How to Retrieve Data from a Textarea with PHP

How to Create a Confirmation Page for an HTML Web Form Using PHP

How to Redirect to Another URL with PHP

How to Create a Search Engine Using PHP

How to Upload Images to a Website Using PHP

How to Upload Files to a Website Using PHP

How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP



HTML Comment Box is loading comments...