How to use magic methods in PHP

Magic methods are special methods that we define in classes to perform some behavior when something special happens.

For example when a property is set, or accessed, or when the object is cloned.

We’ve seen __construct() before.

That’s a magic method.

There are others. For example we can set a “cloned” boolean property to true when the object is cloned:

class Dog {
  public $name;

  public function __clone() {
    $this->cloned = true;
  }
}

$roger = new Dog();
$roger->name = 'Roger';

$syd = clone $roger;
echo $syd->cloned;

Other magic methods include __call(), __get(), __set(), __isset(), __toString() and others.

See the full list here

Download my free PHP Handbook!