Friday, July 5, 2024
HomeLanguagesPhpHow to declare a global variable in PHP?

How to declare a global variable in PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

Syntax:

$variable_name = data;

Below programs illustrate how to declare global variable.

Example 1:




<?php
// Demonstrate how to declare global variable
  
// Declaring global variable
$x = "Geeks";
$y = "for";
$z = "Geeks";
  
// Display value
// Concatenating String
echo $x.$y.$z;
  
?>


Output:

neveropen

Accessing global variable inside function: The ways to access the global variable inside functions are:

  • Using global keyword
  • Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable. This array is also accessible from within functions and can be used to perform operations on global variables directly.

Example 2:




<?php
// Demonstrate how to declare
// global variable
  
// Declaring global variable
$x = "Geeks";
$y = "for";
$z = "Geeks";
$a = 5;
$b = 10;
  
function concatenate() {
    // Using global keyword
    global $x, $y, $z;
    return $x.$y.$z;
}
  
function add() {
    // Using GLOBALS['var_name']
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
  
// Print result
echo concatenate();
echo"\n";
add();
echo $b;
?>


Output:

neveropen
15

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments