PHP __toString() Method with Examples
by TechVidvan Team
Program 1
<html>
<head><title>Demo</title></head>
<body>
<center>
<?php
class Product
{
private $pname;
private $price;
private $qty;
public function __construct($name,$pr,$qt)
{
$this->pname=$name;
$this->price=$pr;
$this->qty=$qt;
}
public function __tostring()
{
//return "<br>This is to String method<br>";
return "Product Name: ".$this->pname.", Price: ".$this->price.", Qty:".$this->qty;
}
}
$obj1=new Product('Limca',50,10);
$obj2=new Product('Water',20,1000);
$obj3=new Product('Frooti',40,100);
// print_r($obj1);
echo $obj1;
echo "<br>";
echo $obj2;
echo "<br>";
echo $obj3;
?>
</center>
</body>
</html>
Tags: PHPphp practicalphp programphp tostring methodtostring methodtostring method in php
TechVidvan Team
TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.