Home Tutorial Php Phpoop PHP toString Function

 
 

PHP toString Function
Posted on: March 4, 2010 at 12:00 AM
In PHP 5.3.0 a method has been introduced called toString(), basic functionality of the method is to print an object, how? current tutorial is trying to focus on this topic.

__toString method in PHP:

In the previous versions of PHP it is not possible to convert an object to a string value, but with the invent of _toString method now it is just a function call away.

This method is called implictly, whenever an object is instantiated we need to pass a string value to the __construct() function (the constructor ) and assign the value to a variable. After instantiation of the object, if we try to print the object, __toString() function is called implicitly and print the value of the member variable.

PHP toString Function Example:

<?php

class A

{

private $var;

public function __construct($var){

$this->var=$var;

}

public function __toString()

{

return $this->var;

}

}

$obj=new A('Hi');

echo $obj;

?>

Output:

Hi

Related Tags for PHP toString Function:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.