Yogesh Chauhan's Blog

How to Access a Global Variable From Inside a Function in PHP?

in PHP on November 11, 2019

As I have discussed in this post that we can not access global variables inside a function as it's outside of their scope. 

But there is a way to do that. We can use reserved keyword "global" inside a function to access their values assigned outside. 

Let's take a look at this example. 


<?php

$x = 5;
$y = 5;

function globVar() {
    global $x, $y;
    $y = $x + $y;
} 

globVar();  // run function
echo $y; // output the new value for variable $y

echo "<p>As you can see the value of variable y has changed even if we performed the calculation inside the function</p>"

;?>

Take a look at the results of the code above in the DEMO link provided at the end of this article.

We can store the global variables in PHP. PHP provided an array to store those values which is called $GLOBALS[index], where index will be the name of the variable we want it to hold.

Also, we can access this array from inside the function as well as we can update the values of global variables directly. 

Take a look at the example below:


<?php
$a = 5;
$b = 10;

function globVar2() {
    $GLOBALS['a'] = $GLOBALS['b'] + $GLOBALS['a'];
}

globVar2();
echo $a; 

echo "<p>As you can see the value of variable a has changed even if we performed the calculation on the GLOBALS[a] inside the function. Checkout the code in the article from the link above.</p>"
?>

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to check if the page is the home page in WordPress?WordPressThe Difference Between isNaN() Method And isNaN() Function In JavaScriptJavaScriptHow to create a pricing table using flex in CSS?CSSRendering Elements in ReactReactThe Differences Between HAVING Clause and WHERE Clause in SQLSQL/MySQLHow to get previous days or next days in PHP?PHP