Lesson :- 7 Global Variables in PHP

🌍 Global Variables in PHP



A global variable is declared outside any function and can be used throughout the PHP script. However, it cannot be accessed directly inside functions unless made global explicitly.

🧠 Why Use Global Variables?

  • To share values (e.g., settings, constants) across multiple functions
  • To reduce code repetition for values used in multiple places

🛠️ Accessing Global Variables Inside a Function

Use the global keyword or the $GLOBALS superglobal array.

$x = 10;
$y = 20;

function sum() {
  global $x, $y;
  echo $x + $y;
}

sum(); // Output: 30
  

🗃️ PHP Superglobal Variables

PHP provides several built-in global arrays, called superglobals. They are accessible anywhere in the script.

Superglobal Description
$GLOBALSAccess global variables inside functions
$_SERVERInformation about headers, paths, and server
$_REQUESTCollect data from form using GET or POST
$_POSTCollect form data via POST method
$_GETCollect data via URL query parameters
$_FILESUsed for file uploads
$_COOKIEAccess cookie values
$_SESSIONUsed to store session values
$_ENVAccess environment variables

🔧 Examples of Superglobals

✅ 1. $GLOBALS

$a = 5;
$b = 10;

function multiply() {
  echo $GLOBALS['a'] * $GLOBALS['b'];
}

multiply(); // Output: 50
  

✅ 2. $_SERVER

echo $_SERVER['SERVER_NAME']; // Output: localhost
  

✅ 3. $_GET

URL: http://example.com/page.php?name=John

echo $_GET['name']; // Output: John
  

✅ 4. $_POST

HTML Form:

<form method="POST">
  <input type="text" name="username">
  <input type="submit">
</form>
  

PHP:

echo $_POST['username'];
  

✅ 5. $_COOKIE & $_SESSION

// Set cookie
setcookie("user", "Alice", time() + 3600);

// Read cookie
echo $_COOKIE["user"]; // Alice

// Start session
session_start();
$_SESSION["username"] = "John";
echo $_SESSION["username"]; // John
  

⚠️ Best Practices

  • Use global and $GLOBALS carefully to avoid conflicts
  • Prefer using parameters and return values for function communication
  • Sanitize and validate all superglobal input like $_GET and $_POST
  • Initialize sessions with session_start() before using $_SESSION

Post a Comment

0 Comments