Scope is where in your code a variable can actually be seen and used — the same idea from Intro to Programming, and PHP is stricter about it than some languages you may have used.
A variable created inside a function only exists inside that function. It disappears the moment the function finishes, and is completely invisible to code outside it:
<?php
function setName() {
$name = "Priya"; // local to setName()
echo $name; // works fine here
}
setName();
// echo $name; // Error — $name doesn't exist out here
?>A variable declared outside every function is in the global scope — but, unlike many languages, a PHP function cannot see a global variable automatically just because it exists:
<?php
$siteName = "Learn Computer Academy";
function showName() {
// echo $siteName; // does NOT work — functions don't see globals by default
}
?>To use a global variable inside a function, it has to be explicitly pulled in with global:
<?php
$siteName = "Learn Computer Academy";
function showName() {
global $siteName;
echo $siteName; // now this works
}
showName();
?>Prefer parameters over global
Relying on global throughout a codebase makes it hard to trace where a value actually comes from. The more common, cleaner pattern — used in nearly every example from here on — is to pass the value in as a parameter instead: function showName($siteName) { echo $siteName; }.
A static variable inside a function keeps its value between calls, instead of resetting every time — useful for counters that live inside a single function:
<?php
function countCalls() {
static $count = 0;
$count++;
echo $count . "\n";
}
countCalls(); // 1
countCalls(); // 2
countCalls(); // 3
?>