
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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
- Related Articles
- How to declare a global variable in C++
- How to declare a global variable in Python?
- How do I declare a global variable in Python class?
- How to declare global variables in Android?
- How to declare global Variables in JavaScript?
- How to declare a variable in MySQL?
- How to declare a variable in C++?
- How to declare a variable in Python?
- How to declare a local variable in Java?
- How to set a global variable in Postman?
- How to create a Global Variable in Postman?
- MySQL how to declare a datetime variable?
- How to define global variable in a JavaScript function?
- How to declare a variable correctly in a MySQLProcedure?\n
- How to declare a variable inside a procedure in MySQL?

Advertisements