Tsallaka zuwa abun ciki
Justice Tech School

Magic Methods

__construct, __destruct, __toString, __get, __set, __call, __invoke and __clone run in special situations. __toString lets an object become a string.

Example
class Money {
  public function __construct(private int $c) {}
  public function __toString(): string { return "$" . number_format($this->c / 100, 2); }
  public function __invoke($x) { return $this->c * $x; }
  public function __get($n) { return "no $n"; }
}
$m = new Money(1999);
echo $m, " ", $m(2), " ", $m->foo, "\n";

Result

$19.99 3998 no foo

Exercise

Convert an object to text.

public function () { }

Quiz Test

Which makes an object callable?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.