What is scope?
It’s nice to start writing again! I had a little too much fun with CodingJs JavaScript exercises, so it’s nice to get back into PHP. I’m doing this by working on my personal website and doing some Perpetual Education (PE) study hall and resource questions.
Scope is best defined as realm of availability. Let’s use the field of vision inside a scope as an example. This visible area is referred to as “field of view” (FOV). The FOV represents the extent of the observable world that can be seen at any given moment through the scope- ah, there’s that word again! Anything outside of that FOV can be said to be outside of scope and unobservable.
My mentor and friend Derek likes to use the nearest fridge to illustrate scope. As an example- if you have guests at your house and they ask for a drink, they would (hopefully) go to the fridge in your home instead of breaking and entering the neighbor’s house!
The different types of scope
Global Scope: This is the default scope for variables declared at the top-level- outside of any
class
, block i.e{}
orfunction
.A variable declared in global scope is accessible from anywhere in the script except within functions or methods, unless explicitly declared as global within those functions.
In the example below, I’ve declared a
for
loop in the global context. The\$i
variable has block scope, and in this case that block is the global code block- you can indeed think of the main script (global context) as one big code block{}
:<?php // global context for ($i = 0; $i < 10; $i++) { echo $i . " "; } echo "Final value of i: " . $i; // This will output: Final value of i: 10 ?>
**note: PHP traditionally did not have true block scope until PHP 7. This came with the introduction of
finally
blocks intry
statements and withcatch
blocks**Local Scope: Variable(s) declared within a function or a block (i.e
{}
) have local scope and are only accessible within that function or block. They are not accessible outside of it. Trying to access a variable outside of scope will result in an error.<?php function test() { $localVar = "I'm local!"; echo $localVar; // Accessible within the function } test(); // Outputs: I'm local! echo $localVar; // Error: Undefined variable $localVar ?>
Function Scope: Specific to languages like JavaScript, where variables declared within a function are only available within that function.
<?php function test() { if (true) { $blockVar = "I'm in a block!"; echo $blockVar; // Accessible within the block } echo $blockVar; // Accessible because PHP does not have true block scope (except within `for`, `while`, and `foreach` loops) } test(); // Outputs: I'm in a block! I'm in a block! ?>
Block Scope: Specific to languages that support block-level scope (like JavaScript with
let
andconst
, or modern versions of PHP), where variables declared within a block are only available within that block.<?php function test() { if (true) { $blockVar = "I'm in a block!"; echo $blockVar; // Accessible within the block } echo $blockVar; // Accessible because PHP does not have true block scope (except within `for`, `while`, and `foreach` loops) } test(); // Outputs: I'm in a block! I'm in a block! ?>
Class Scope: Variables declared within a class (such as properties) are accessible within the class and its methods. We also have the following visibility modifiers for class properties (variables within the class):
Public- Because the class property and method (
$name
andgetDetails()
) are declaredpublic
, we can access them “from outside” the class- without instantiating the class using thenew
keyword (and creating an object from said class).Protected- Class members declared with the protected visibility modifier are only accessible within the class and any subclasses (a class extended from the parent class). In the case of the
Student
class,getId()
and$id
are protected.Private- Class members declared private are only accessible within the class.
$gpa
andgetGpa()
are private members of theStudent
class (a property and method respectively).
<?php
class Student {
// Public property: Can be accessed from outside the class
public $name;
// Protected property: Can be accessed only within the class and by inheriting classes
protected $id;
// Private property: Can be accessed only within the class
private $gpa;
// Constructor to initialize the student object
public function __construct($name, $id, $gpa) {
$this->name = $name;
$this->id = $id;
$this->gpa = $gpa;
}
// Public method: Can be called from outside the class
public function getDetails() {
echo "Student Name: " . $this->name . "\n";
echo "Student ID: " . $this->id . "\n";
echo "GPA: " . $this->getGpa() . "\n"; // Accessing private property through a public method
}
// Protected method: Can be called only within the class and by inheriting classes
protected function getId() {
return $this->id;
}
// Private method: Can be called only within the class
private function getGpa() {
return $this->gpa;
}
// Public method to demonstrate access to protected and private methods
public function showProtectedAndPrivateData() {
echo "Student ID (via protected method): " . $this->getId() . "\n";
echo "GPA (via private method): " . $this->getGpa() . "\n";
}
}
// Creating an object of Student
$student = new Student("John Doe", "S12345", 3.8);
// Accessing public property
echo $student->name . "\n"; // Output: John Doe
// Accessing public method
$student->getDetails();
// Accessing protected and private properties/methods from outside the class will cause an error
// echo $student->id; // Fatal error
// echo $student->gpa; // Fatal error
// $student->getId(); // Fatal error
// $student->getGpa(); // Fatal error
// Accessing protected and private methods through a public method
$student->showProtectedAndPrivateData(); // Output: Student ID (via protected method): S12345
// GPA (via private method): 3.8
?>
Resources
CodingJs *Beware: some of the sandbox tests aren’t accurate. Use at your own risk*.
Web Development Professional Network Perpetual Education (PE).
My Mentor and friend Derek’s website.
Great guy, creator of PE and a real HTML/CSS heavyweight.