PHP toString Function


 

PHP toString Function

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.

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

Ads