PHP access global variable in function

Today, We want to share with you PHP access global variable in function.In this post we will show you PHP $GLOBALS (super global) variable, hear for Accessing a Global Variable Inside a Function we will give you demo and example for implement.In this post, we will learn about How to assign global variable value in a function in php? with an example.

PHP access global variable in function

There are the Following The simple About PHP access global variable in function Full Information With Example and source code.

As I will cover this Post with live Working example to develop how to use global variable inside function in php, so the php global variable in function for this example is following below.

Way : 1 php access variable outside function

// global scope
$product_data = "Old Product Data Value";

function product_function($data) {
   global $product_data;
   $product_data = "New Data value";
}

function category_function(){
    global $product_data;
    product_function("test test test");
}

Way : 2 php set global variable in function

function foo(){
  $GLOBALS['product_id'] = 'product_id';
}
function bar(){
  echo $GLOBALS['product_id'];
}
foo();
bar();

Way : 3 php global variable across files


Way : 4 Declaring a global variable inside a function

// global scope
$product_id = 1;

product_function($rid){
   global $product_id;
   $product_id = $rid;
}

category_function(){
    global $product_id;
    sendValue($product_id);
}

Way : 5 PHP Global Variable Example: Playing with Scope in PHP

$global = "I am a global variable because I wasn't defined inside a function.";

product_function();
category_function($global);
function product_function() { 
     global $global; 
     echo $global;
}

function category_function($global) {
     echo $global;
}

function category_else_global() {
    global $category_global;
    $category_global = "I'm global becuase the word global was used inside a function.";
}
category_else_global();
echo $category_global;
Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP access global variable in function.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment