Topics Object-Oriented PHP Magic Methods & Advanced OOP
advanced 14 min read

Magic Methods & Advanced OOP

__construct, __destruct, __get, __set, __call, __toString, __invoke, and more.

Magic Methods

class Magic {
// Called when creating object
public function __construct() { }
// Called when object is destroyed
public function __destruct() { }
// Called when accessing inaccessible property
public function __get(string \$name): mixed { }
// Called when setting inaccessible property
public function __set(string \$name, mixed \$value): void { }
// Called when calling inaccessible method
public function __call(string \$name, array \$args): mixed { }
// Static version of __call
public static function __callStatic(string \$name, array \$args): mixed { }
// Called when echoing the object
public function __toString(): string { }
// Called when using object as function
public function __invoke(mixed ...\$args): mixed { }
// Called when cloning
public function __clone(): void { }
// Called by serialize
public function __serialize(): array { }
public function __unserialize(array \$data): void { }
}

Example: Active Record-style access

class Model {
private array \$attributes = [];
public function __get(string \$key): mixed {
return \$this->attributes[\$key] ?? null;
}
public function __set(string \$key, mixed \$value): void {
\$this->attributes[\$key] = \$value;
}
}

Examples

<?php
class CallableClass {
    public function __invoke(string $msg): string {
        return "Called with: $msg";
    }
}
$obj = new CallableClass();
echo $obj('test'); // Called with: test

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.