OOP — Static Methods/Properties & Namespaces
static members belong to the class, not each object. Call with ClassName::method() without creating an instance.
Static Methods and Properties
static members belong to the class, not each object. Call with ClassName::method() without creating an instance.
Real-life example: Static is the school bell — one bell for all classrooms, not a separate bell per student.
<?php
class Counter {
public static int $count = 0;
public static function increment(): void {
self::$count++;
}
}
Counter::increment();
Counter::increment();
echo Counter::$count; // 2
?>Namespaces
Namespaces organize code and avoid name clashes. Declare with namespace App\Models; import with use App\Models\User;
Real-life example: Namespaces are apartment numbers — User in 5A and User in 5B are different people.
<?php
namespace App\Services;
class Mailer {
public function send(string $to, string $body): void {
echo "Sent to $to";
}
}
// another file:
// use App\Services\Mailer;
// $mail = new Mailer();
?>Iterables
PHP 7.1+ iterable type hint accepts arrays or Traversable objects. foreach works on any iterable.
Real-life example: Iterable is anything you can walk through with foreach — a list, a queue, or a custom collection.
<?php
function printLessons(iterable $lessons): void {
foreach ($lessons as $lesson) {
echo "- $lesson\n";
}
}
printLessons(["Intro", "Syntax", "MySQL"]);
// Generator is iterable
function rangeGen(int $n): Generator {
for ($i = 1; $i <= $n; $i++) yield $i;
}
printLessons(rangeGen(3));
?>