Where and why do we use __toString() in PHP?
__toString()
is called when an object is passed to a function (esp echo()
or print()
) when its context is expected to be a string. Since an object is not a string, the __toString()
handles the transformation of the object into some string representation.
In addition to all existing answers, here's an example, :
class Assets{
protected
$queue = array();
public function add($script){
$this->queue[] = $script;
}
public function __toString(){
$output = '';
foreach($this->queue as $script){
$output .= '<script src="'.$script.'"></script>';
}
return $output;
}
}
$scripts = new Assets();
It's a simple class that helps you manage javascripts. You would register new scripts by calling $scripts->add('...')
.
Then to process the queue and print all registered scripts simply call print $scripts;
.
Obviously this class is pointless in this form, but if you implement asset dependency, versioning, checks for duplicate inclusions etc., it starts to make sense (example).
The basic idea is that the main purpose of this object is to create a string (HTML), so the use of __toString in this case is convenient...
You don't "need" it. But defining it allows your object to be implicitly converted to string, which is convenient.
Having member functions that echo
directly is considered poor form because it gives too much control of the output to the class itself. You want to return strings from member functions, and let the caller decide what to do with them: whether to store them in a variable, or echo
them out, or whatever. Using the magic function means you don't need the explicit function call to do this.