dots Created with Sketch.
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>"
?>
amazon

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 add Read More Read Less Button using JavaScript? #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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
How to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScriptHow to Access a Global Variable From Inside a Function in PHP?PHPHow to add Local State to a Class in React?ReactModules and its Core features in JavaScriptJavaScriptHow to avoid element shift on border change while hovering in CSS?CSSHow to show confirmation alerts with OK and cancel buttons using Swift 5?Swift