YogeshChauhan . com

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>"
?>
dreamhost

Most Read

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

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

The difference between 400(4xx) and 500(5xx) errorsMiscHow to make HTML form interactive and using CSS?CSSSorting Object Arrays in JavaScriptJavaScriptHow to scroll contents of a an element vertically using JavaScript?JavaScriptHow to Use Aggregate Functions (MIN, MAX, SUM, AVG, COUNT) to Summarize Data in SQL?SQL/MySQLDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPress