Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 147 ยท Object-Oriented PHP

Magic Methods

Learn PHP magic methods - __toString, __get and __set, __isset, __call and __callStatic, __invoke, __clone, __serialize - and when magic hurts readability.

Magic methods are methods with special names, all starting with two underscores, that PHP calls for you when something specific happens to an object. You never write $obj->__toString() yourself; PHP calls it when the object is used as a string. You don't call __get(); PHP calls it when code reads a property that isn't accessible. You've already met two magic methods: __construct() and __destruct() from Constructors and Destructors.

Magic methods let objects plug into the language: be echoed, be called like functions, respond to properties and methods that don't exist, control how they're copied and serialized. Frameworks use them heavily. They're also the easiest way to write code that nobody can follow, because the behavior is invisible at the call site. This lesson covers each magic method with a realistic example, and ends with advice on when not to use them.

Method Called when
__toString() the object is used as a string
__get($name), __set($name, $value) reading or writing an inaccessible property
__isset($name), __unset($name) isset()/empty() or unset() on an inaccessible property
__call($name, $args), __callStatic(...) calling an inaccessible method
__invoke(...) the object is called like a function
__clone() after the object is copied with clone
__serialize(), __unserialize() serialize() / unserialize()
__debugInfo() var_dump()
__set_state() var_export() output is evaluated

Inaccessible means either the property or method doesn't exist, or it exists but is private/protected and you're outside the class. All magic methods except __construct(), __destruct() and __clone() must be public.

__toString: objects as strings

When an object appears where PHP needs a string (in echo, concatenation, string interpolation, or a string parameter), PHP calls its __toString() method, which must return a string:

PHP Using __toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Any class with a __toString() method automatically implements the Stringable interface (PHP 8.0), so you can type-hint string|Stringable for "anything that can become a string".

Note the explicit (string) cast before calling label(). Without strict_types, PHP would convert the object automatically; with it, passing an object to a string parameter is a TypeError. An object without __toString() can't become a string at all: echo new stdClass(); throws Object of class stdClass could not be converted to string.

__toString() is great for value objects whose string form is obvious (money, email addresses, URLs, dates). For anything else, a named method like format() or toHtml() is clearer, especially when there's more than one reasonable way to display the object.

__get, __set, __isset and __unset: property overloading

These four methods handle access to properties that don't exist or aren't visible. A classic use is a small object that stores its data in an array:

PHP Property overloading with __get and __set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The (__get ...) and (__set ...) lines show exactly when PHP calls each method. Without __isset(), isset($config->debug) would always return false, because from the outside there's no debug property; isset() and empty() rely on it. Implement __isset() whenever you implement __get().

Important details:

  • These methods are called only for inaccessible properties. Reading the private $values from outside triggers __get('values'); reading a public property never does.
  • __get() returns by value, so $config->list[] = 'x'; modifies a temporary copy and PHP emits a notice: Indirect modification of overloaded property. Return by reference (public function &__get(...)) if you really need it.
  • Without __set(), writing an unknown property creates a dynamic property. That's deprecated since PHP 8.2 (Creation of dynamic property ... is deprecated) unless the class has the #[\AllowDynamicProperties] attribute or is stdClass.

For a fixed set of computed or validated properties, PHP 8.4 property hooks are almost always better than __get()/__set(): they're declared, typed, visible to IDEs and static analysers, and much faster. Property overloading is for truly dynamic names, such as wrapping a data array or an API response.

__call and __callStatic: method overloading

__call() runs when code calls an inaccessible instance method; __callStatic() does the same for static calls. They receive the method name and an array of arguments. Proxies, decorators and "fluent" builders use them:

PHP A logging proxy with __call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The proxy adds logging around any method of any object without knowing them in advance. $this->target->$method(...$arguments) calls a method whose name is in a variable and unpacks the argument list.

__callStatic() works the same way for ClassName::anything() calls. Some frameworks use it to offer static-looking "facades" that forward calls to a real object:

PHP __callStatic and named-pattern methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Always throw a BadMethodCallException (or Error) for names you don't handle. A __call() that silently returns null for unknown methods turns every typo into a hard-to-find bug.

__invoke: callable objects

If a class defines __invoke(), its objects can be called like functions. They pass the callable type check and work anywhere a callback is expected, like array_map() or usort(). Unlike a plain closure, an invokable object can have a name, a type, configuration and methods:

PHP Invokable objects as callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Invokable classes are common for single-action controllers, middleware, validation rules and event listeners: one class, one job, called with $handler($request).

__clone: customizing copies

clone $obj makes a shallow copy: properties holding objects still point at the same objects as the original. After copying, PHP calls __clone() on the new object, where you can deep-copy what needs it:

PHP
class Invoice
{
    public function __construct(public DateTimeImmutable $date, public Customer $customer) {}

    public function __clone(): void
    {
        $this->customer = clone $this->customer; // give the copy its own Customer
    }
}

__clone() is covered in depth, with runnable examples of shallow and deep copies, in Comparing, Copying and Serializing Objects.

__serialize and __unserialize

serialize() turns a value into a string that unserialize() can turn back into the same value; frameworks use it to store objects in caches and sessions. By default all properties are saved. __serialize() returns an array of exactly what to save, and __unserialize() restores the object from that array. This is how you leave out things that can't or shouldn't be stored, such as database connections, file handles or passwords:

PHP Controlling serialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Without __serialize(), this would fail, because PDO objects refuse to be serialized (Serialization of 'PDO' is not allowed). The serialized string shows the format: O: for object, the class name, and the saved array.

You may also see the older __sleep() and __wakeup() pair and the Serializable interface in legacy code. Prefer __serialize()/__unserialize() (PHP 7.4+). Never call unserialize() on data from users; the reasons are explained in Comparing, Copying and Serializing Objects.

__debugInfo and __set_state

Two smaller magic methods help with debugging:

  • __debugInfo() returns the array var_dump() shows instead of the real properties. Use it to hide secrets or to show a friendlier view.
  • __set_state(array $properties) is a static method that var_export() output calls to rebuild an object when the exported code is evaluated.
PHP Hiding secrets from var_dump

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

var_dump() now shows the masked key. Note that print_r() and var_export() do not use __debugInfo(). The #[\SensitiveParameter] attribute (PHP 8.2) hides the argument in stack traces too, which matters because uncaught exceptions often end up in logs.

When magic hurts readability

Magic methods are tools for building tools: proxies, ORMs, test doubles, configuration bags. In everyday application code, prefer explicit code:

  • Your IDE can't see magic. $user->fullName backed by __get() has no autocompletion, no "go to definition", and no type. Static analysers like PHPStan flag it as an error unless you add @property DocBlock annotations.
  • Typos fail late or not at all. A misspelled real method fails at once with Call to undefined method. A misspelled magic method may reach __call() and do something unexpected.
  • They're slower. A magic call goes through extra machinery; a real method or property is faster.
  • They hide behavior. Reading $a->b = 5; you can't tell whether it's a plain assignment, a validation step, or a database write.

A good order of preference: plain properties and methods, then property hooks or interfaces, and only then magic methods. __toString(), __invoke(), __clone() and __serialize() are the exceptions: they have clear, well-defined jobs and are worth using whenever they fit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class has a public property $name and a __get() method. What does reading $obj->name do?

    __get() runs only for inaccessible properties, meaning missing ones or non-visible ones. Accessible properties are read normally.
  2. 2. Why should a class that implements __get() usually implement __isset() too?

    isset() and empty() don't call __get(). They call __isset(), and without it they return false for every overloaded property.
  3. 3. What makes $filter($item) work when $filter is an object?

    An object with __invoke() can be called like a function and passes is_callable() checks, so it can be used as a callback.
  4. 4. What should __call() do with a method name it doesn't recognize?

    Silently returning null hides typos. Throwing makes mistakes visible immediately, just like a normal undefined-method error.
  5. 5. Which function uses __debugInfo()?

    Only var_dump() uses the array returned by __debugInfo(). print_r() and var_export() show the real properties.

Summary

  • Magic methods have names starting with __; PHP calls them automatically when something specific happens to an object.
  • __toString() turns an object into a string and makes it Stringable.
  • __get(), __set(), __isset() and __unset() handle inaccessible properties; always pair __get() with __isset(). Prefer property hooks for known properties.
  • __call() and __callStatic() handle inaccessible methods; throw BadMethodCallException for names you don't support.
  • __invoke() makes objects callable, which is ideal for configurable callbacks and single-action classes.
  • __clone() adjusts copies; __serialize()/__unserialize() control what is stored; __debugInfo() shapes var_dump() output.
  • Magic hides behavior from people and tools. Use it for infrastructure, and prefer explicit properties and methods in application code.

Next: Namespaces