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 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
How to remove trailing characters from a string using JavaScript?JavaScriptWordPress: How to find all posts from a custom post type with specific custom field?WordPressWhere is the PHP log file located on Mac OS?PHPHow to add multiple components in React app?ReactContent types in DrupalDrupalHow to display and animate image on scroll using JavaScript?JavaScript