Tizag.com Webmaster Tutorials - A collection of webmaster tutorials from HTML to PHP.

Saturday, January 23, 2010

Simple example with __toString() - PHP

__toString()



__toString() is a magic function, and allows you to set a string value for the object that will be used if the object is ever used as a string.

<?php
class TotalPrice{
protected $price, $quantity, $total;

public function __construct($productPrice, $productQuantity){
$this->price = $productPrice;
$this->quantity = $productQuantity;
$this->calculatePrice();
}

protected function calculatePrice(){
$this->total = ($this->price * $this->quantity);
}

public function __toString(){
return "Total Price :: ".$this->total;
}

}

$totalPrice = new TotalPrice("2.00", "6");
echo $totalPrice;
?>

No comments: