0
0
PHPprogramming~5 mins

Variable scope in functions in PHP

Choose your learning style9 modes available
Introduction

Variable scope tells us where a variable can be used in a program. It helps keep things organized and avoids mistakes.

When you want to use a variable only inside a function and not outside.
When you want to use a variable defined outside a function inside it.
When you want to avoid changing a variable outside a function by mistake.
When you want to share a variable between different functions carefully.
When you want to understand why a variable inside a function is not changing the outside one.
Syntax
PHP
<?php
function functionName() {
    // local variable
    $var = 'value';
}

// global variable
$var = 'value';

function anotherFunction() {
    global $var; // to use global variable inside function
    // now $var refers to the global one
}
?>

Variables inside functions are local by default.

Use global keyword to access global variables inside functions.

Examples
This shows a variable inside a function. It only works inside that function.
PHP
<?php
function greet() {
    $message = "Hello"; // local variable
    echo $message;
}
greet();
This shows how to use a global variable inside a function with global.
PHP
<?php
$message = "Hi"; // global variable
function greet() {
    global $message;
    echo $message;
}
greet();
Local variable inside function does not change the global one.
PHP
<?php
$message = "Hi";
function greet() {
    $message = "Hello"; // local variable, different from global
    echo $message;
}
greet();
echo $message;
Sample Program

This program shows how global and local variables behave inside functions. It prints the message from global, changes it, then shows local variable inside another function does not affect global.

PHP
<?php
$message = "Good morning"; // global variable

function sayMessage() {
    global $message; // use global variable
    echo $message . "\n";

    $message = "Good night"; // change global variable
}

sayMessage();
echo $message . "\n"; // check changed global variable

function localTest() {
    $message = "Local hello"; // local variable
    echo $message . "\n";
}

localTest();
echo $message . "\n"; // global variable unchanged here
OutputSuccess
Important Notes

Without global, variables inside functions are separate from global ones.

Changing a local variable does not affect the global variable with the same name.

Use global variables carefully to avoid confusion.

Summary

Variables inside functions are local by default.

Use global keyword to access and change global variables inside functions.

Local variables do not affect global variables with the same name.