PHP Scope, Static and Constants
Variables created inside a function are local. Use global to reach a global one, static to keep a value between calls, and define/const for constants.
ExamplePHP
<?php
$x = 10;
function noAccess() {
return isset($x) ? "sees x" : "no x here";
}
function withGlobal() {
global $x;
return $x + 1;
}
function counter() {
static $n = 0;
return ++$n;
}
echo noAccess(), "\n";
echo withGlobal(), "\n";
echo counter(), counter(), counter(), "\n";
define("SITE", "WeCode");
const VERSION = "1.0";
echo SITE, " ", VERSION, "\n";
echo defined("SITE") ? "defined" : "missing", "\n";Output
no x here 11 123 WeCode 1.0 defined
Quick check
What does static do to a variable inside a function?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.