You are on page 1of 2

In PHP, scope refers to the visibility of variables and functions within different parts of a script.

Understanding scope is crucial for organizing and maintaining code, as it determines where variables
and functions can be accessed and modified. There are several types of scope in PHP:

Global Scope: Variables declared outside of any function or class have global scope. They can be
accessed from anywhere within the script, including inside functions and classes. However, to modify
global variables within functions, you need to use the global keyword or the $GLOBALS array.

phpCopy code

$globalVar = 10; function modifyGlobalVar() { global $globalVar; $globalVar = 20; } modifyGlobalVar();


echo $globalVar; // Output: 20

Function Scope: Variables declared within a function have function scope. They are only accessible
within the function in which they are defined.

phpCopy code

function foo() { $localVar = 5; echo $localVar; } foo(); // Output: 5 // echo $localVar; // This would cause
an error because $localVar is not defined in this scope

Static Variables: Variables declared as static within a function retain their value between function calls.
They are initialized the first time the function is called and then maintain their value across subsequent
calls.

phpCopy code

function increment() { static $counter = 0; $counter++; echo $counter . " "; } increment(); // Output: 1
increment(); // Output: 2 increment(); // Output: 3

Class Scope: In object-oriented PHP, variables and methods declared within a class have class scope.
They are accessed using the object of the class (instance variables) or the class itself (static
variables/methods).

phpCopy code

class MyClass { public $instanceVar = 10; public static $staticVar = 20; public function printInstanceVar()
{ echo $this->instanceVar; } public static function printStaticVar() { echo self::$staticVar; } } $obj = new
MyClass(); echo $obj->instanceVar; // Output: 10 echo MyClass::$staticVar; // Output: 20 $obj-
>printInstanceVar(); // Output: 10 MyClass::printStaticVar(); // Output: 20

Namespace Scope: With the introduction of namespaces in PHP, variables, functions, and constants can
have scope within a particular namespace, restricting their visibility to code within that namespace.

These are the main scopes in PHP. Understanding and properly managing scope is essential for writing
maintainable and structured PHP code.

You might also like