Junior
What are the variable scope areas in PHP?
sobes.tech AI
Answer from AI
- Global: Variables declared outside functions or classes are accessible in the global scope. Inside functions, they need to be accessed using the
globalkeyword or the superglobal array$GLOBALS. - Local: Variables declared inside a function are only accessible within that function.
- Static: Variables declared with the
statickeyword inside a function retain their value between function calls. - Function/Method parameters: Parameters passed to a function or method are only accessible within that function/method as local variables.
- Class properties: Class properties (declared with
public,protected,privatemodifiers) are accessible within the context of an object of that class.
<?php
// Global scope
$globalVar = 'I am global';
function testScope() {
// Local scope
$localVar = 'I am local';
// Accessing global variable using global keyword
global $globalVar;
echo $globalVar . "\n";
// Accessing global variable using $GLOBALS
echo $GLOBALS['globalVar'] . "\n";
echo $localVar . "\n";
// echo $staticVar; // Error: undefined variable
}
function testStatic() {
// Static scope
static $staticVar = 0;
$staticVar++;
echo "Static variable: " . $staticVar . "\n";
}
function testParameters($param) {
// Parameter scope
echo "Parameter: " . $param . "\n";
}
testScope();
testStatic(); // Output: Static variable: 1
testStatic(); // Output: Static variable: 2
testParameters('Hello');
class MyClass {
public $publicProperty = 'I am public';
protected $protectedProperty = 'I am protected'; // Accessible within the class and subclasses
private $privateProperty = 'I am private'; // Accessible only within the class
public function accessProperties() {
echo $this->publicProperty . "\n";
echo $this->protectedProperty . "\n";
echo $this->privateProperty . "\n";
}
}
$obj = new MyClass();
$obj->accessProperties();
// echo $obj->privateProperty; // Error: Cannot access private property
?>