devnotes.

Constructors, Destructors, and Magic Methods

__construct() runs automatically when an object is created; __destruct() runs when the object is destroyed or the script ends — useful for cleanup like closing a file handle.

class Logger
{
    private $handle;

    public function __construct(string $file)
    {
        $this->handle = fopen($file, 'a');
    }

    public function __destruct()
    {
        fclose($this->handle);
    }
}

PHP has several other 'magic methods' (all prefixed with __) that let you hook into object behavior:

  • __toString() — defines how an object converts to a string, e.g. echo $product;
  • __get($name) / __set($name, $value) — intercept access to undefined or inaccessible properties
  • __call($name, $args) — intercept calls to undefined methods (used heavily by frameworks for dynamic APIs)
  • __invoke(...$args) — lets an object be called like a function: $product(...)
  • __clone() — customize behavior when an object is cloned with the clone keyword
class Money
{
    public function __construct(private int $cents) {}

    public function __toString(): string
    {
        return number_format($this->cents / 100, 2);
    }
}
echo new Money(1999); // '19.99'

Magic methods are powerful but should be used sparingly — overusing them can make code harder to follow, since the behavior isn't visible from a simple method list.

PHP Magic Methods: __construct, __toString & More | DevNotes