Elevate your OOP skills - Dive into advanced techniques for powerful, flexible PHP code!
Advanced OOP in PHP builds on the basics, offering tools like static methods, abstract classes, and reflection to create robust, reusable, and maintainable applications.
Define methods callable without instantiation using static.
class Math {
public static function add($a, $b) {
return $a + $b;
}
}
echo Math::add(5, 3); // Outputs: 8A single static method in context.
class Logger {
public static function log($message) {
echo "Log: $message";
}
}
Logger::log("Error occurred"); // Outputs: Log: Error occurredPass arguments as usual.
class Converter {
public static function toCelsius($fahrenheit) {
return ($fahrenheit - 32) * 5 / 9;
}
}
echo Converter::toCelsius(98.6); // Outputs: 37Use static properties, accessed with self::.
class Counter {
public static $count = 0;
public static function increment() {
self::$count++;
return self::$count;
}
}
echo Counter::increment(); // Outputs: 1
echo Counter::increment(); // Outputs: 2Static members are shared, but can be overridden.
class ParentClass {
public static $value = "Parent";
public static function getValue() {
return self::$value;
}
}
class ChildClass extends ParentClass {
public static $value = "Child";
}
echo ParentClass::getValue(); // Outputs: Parent
echo ChildClass::getValue(); // Outputs: ChildDefine a blueprint with abstract—cannot be instantiated.
abstract class Shape {
abstract public function area();
}
class Rectangle extends Shape {
public $width, $height;
public function area() {
return $this->width * $this->height;
}
}
$rect = new Rectangle();
$rect->width = 5;
$rect->height = 3;
echo $rect->area(); // Outputs: 15Specify contracts with interface.
interface Printable {
public function print();
}
class Document implements Printable {
public function print() {
echo "Printing document...";
}
}
$doc = new Document();
$doc->print(); // Outputs: Printing document...Implement Iterator for custom looping.
class MyList implements Iterator {
private $items = [];
private $position = 0;
public function __construct($items) {
$this->items = $items;
}
public function current() { return $this->items[$this->position]; }
public function key() { return $this->position; }
public function next() { $this->position++; }
public function rewind() { $this->position = 0; }
public function valid() { return isset($this->items[$this->position]); }
}
$list = new MyList(["a", "b", "c"]);
foreach ($list as $item) {
echo "$item ";
} // Outputs: a b cUse == (properties) or === (identity).
class User {
public $id;
public function __construct($id) {
$this->id = $id;
}
}
$u1 = new User(1);
$u2 = new User(1);
echo $u1 == $u2 ? "Equal" : "Not equal"; // Outputs: Equal
echo $u1 === $u2 ? "Same" : "Not same"; // Outputs: Not sameDefine immutable values with const.
class Config {
const MAX_USERS = 100;
}
echo Config::MAX_USERS; // Outputs: 100Prevent overriding or extension.
final class Immutable {
final public function lock() {
echo "Locked!";
}
}
class Test extends Immutable {} // Error: Cannot extend final classDuplicate with clone.
class Item {
public $name = "Book";
public function __clone() {
$this->name .= " (copy)";
}
}
$original = new Item();
$copy = clone $original;
echo $copy->name; // Outputs: Book (copy)Inspect classes dynamically with ReflectionClass.
class Sample {
public $data = "Test";
public function run() {}
}
$reflection = new ReflectionClass("Sample");
echo "Methods: " . implode(", ", $reflection->getMethods()) . "<br>";
echo "Properties: " . implode(", ", array_keys($reflection->getProperties()));
// Outputs: Methods: run, Properties: data| Technique | Key Feature | Example Use Case |
|---|---|---|
| Static Methods | No instantiation | Utilities |
| Abstract Classes | Enforce structure | Base templates |
| Interfaces | Contract enforcement | Multiple implementations |
| Reflection | Runtime inspection | Debugging, frameworks |
- Static: Use sparingly—prefer instance methods for state.
- Abstraction: Balance flexibility and enforcement.
- Constants: Use for fixed values (e.g., settings).
- Cloning: Handle deep copies with
__clone().
abstract class Entity {
protected $id;
public function __construct($id) {
$this->id = $id;
}
abstract public function describe();
}
class Product extends Entity {
public function describe() {
return "Product ID: $this->id";
}
}
$prod = new Product(123);
echo $prod->describe(); // Outputs: Product ID: 123