__invoke, __clone and __toString Explained
This is the last post in the series, PHP Reserved Functions. In this post I am going to explain the __invoke, __clone and __toString functions.
Same as other magic functions, these functions also adds some magic functionality to your code. Lets get into each one.
1) __invoke
__invoke function will call when you tries to call the object of the class as function. Lets have a look at below example:
<?php class newClass { function __invoke($var) { echo "In __invoke functions. ". $var; } } $object = new newClass(); $object('abc'); ?>
Output : In __invoke functions abc;
2) __clone
__clone will call once you perform the clone of the object. __clone will call once the cloning of the object is completed.
__clone will create just a copy of the object with reference to the original variables.
__clone will create just a copy of the object with reference to the original variables. So basically __clone is useful to changes the values of the cloned objects’ variables.
Lets have a look at below example:
<?php class Object { public $val=1; function __clone() { $this->val = $this->val+1; } } $obj = new Object(); $obj2 = clone $obj; echo $obj->val; echo "<br />"; echo $obj2->val; ?>
Output: 1 2
3) __toString
__toString function will decide how the class shold behave when we treat the class as a string. Like echoing the object.
Note: __toString must return a string otherwise it will return a fatal E_RECOVERABLE_ERROR.
let’s have a look at below example:
<?php class Object { $name = ''; fucntion __construct() { $this->name = 'test'; } function __toString() { return $this->name; } } $Obj = new Object(); echo $Obj; ?>
Output: test
Hope you find this searies helpful for you, let us know your suggestion on this.

