SyntaxStudy
Sign Up
PHP Variable Scope & Constants
PHP Beginner 1 min read

Variable Scope & Constants

Variable Scope & Constants

Scope

PHP variables are local to functions by default. Use global $var to access global variables inside a function, or pass as parameters (preferred).

Constants

Defined with define() or const. Constants are global and cannot be changed.

Static Variables

static $count = 0 — persists between function calls.

Example
<?php
$globalVar = "I am global";

function test() {
    global $globalVar;       // declare global
    echo $globalVar;
}

// Constants
define("SITE_NAME", "LearnCode");
const VERSION = "1.0.0";

echo SITE_NAME;  // LearnCode (no $)
echo VERSION;    // 1.0.0

// Static
function counter() {
    static $count = 0;
    return ++$count;
}
echo counter(); // 1
echo counter(); // 2
echo counter(); // 3
?>