![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to declare a global variable in PHP?
A global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global.
Example
The code is as follows wherein we can see how to declare a global variable in PHP−
<?php $val = 1; function display() { GLOBAL $val; $val++; print "Value = $val"; } display(); ?>
Output
This will produce the following output−
Value = 2
Example
Let us now see another example−
<?php $a = 2; $b = 3; function display() { global $a, $b; $b = $a + $b; } display(); echo $b; ?>
Output
This will produce the following output−
5
Advertisements