pTutorial

New way to learn PHP

PHP5 __toString() method

__toString() method

PHP5 introduce magic method named __toString (leading double underscore) that is automatically called so that, it is called magic method.

__toString method or function is used to represent the object of any class in the form of the string following example explaining the concept of __toString method.

Problem without __toString() method

<?php

class Computer 
{
function __construct($name)
{
$this->name = $name;
}
private $name;
}
$obj = new Computer("Sony vaio");
print $obj;

?>

Output

Catchable fatal error: Object of class Computer could not be converted to string in D.

If you try to print the object following error will occur, To remove this error use magic method __toString() as shown below.

__toString() method

Solution of above problem

<?php
class Computer {
function __construct($name)
{
$this->name = $name;
}
function __toString()
{
return $this->name;
}
private $name;
}
$obj = new Computer("Sony Vaio");
print $obj;

?>

Output

Sony vio

Now you can easily print the object with the help of tostring method as shown below without any error.


QUOTES OF THE DAY

A single death is tragedy, a million death is a static.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER