Magic Methods in PHP

The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

Eg: The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted

__toString
<?php

class TestClass
{
public $foo;

public function __construct($foo)
{
$this->foo = $foo;
}

public function __toString()
{
return $this->foo;
}
}

$class = new TestClass(‘Hello’);
echo $class;

?>

OUTPUT :
Hello

Eg: The __invoke() method is called when a script tries to call an object as a function.

__invoke
<?php
class CallableClass
{
public function __invoke($x)
{
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

OUTPUT :
int(5)
bool(true)