Jump to content

Problem with __toString


KevinM1

Recommended Posts

I'm still in the process of creating my work's online store.  Since we're small, my boss decided that the design shouldn't be fully automated, so upon checkout, we're sent an e-mail with the order the customer wants, which we then use to contact our distributor in order to fulfill that order (clunky and inefficient, I know...not my choice).  I figured the easiest way to put a person's shopping cart in an e-mail would be to use the __toString magic method.  Unfortunately, I keep getting 'Object id #1' instead of the products in my cart. 

Here's the relevant bits of ShoppingCart code:
[code]
<?

class ShoppingCart{
  private $Cart = array();

  public function addProduct($name, $price, $quantity){
      $this -> Cart[] = new Product($name, $price, $quantity);
  }
.
.
.
public function getTotal(){
      $total = 0;

      foreach($this -> Cart as $value){
        $total += $value -> getPrice();
      }

      return $total;
  }

  public function __toString(){
      $message = NULL;
      $message .= "Name:\tQuantity\tPrice:\n";

      foreach($this -> Cart as $value){
        $message .= "{$value->getName()}\t{$value->getQuan()}\t{$value->getPrice()}\n";
      }

      $message .= "\t\t\t--------\nTotal:\t\t{$this->getTotal()}";
      return $message;
  }
.
.
.
?>
[/code]

And here's my checkout script:
[code]
<?php

#checkout.php

include('../php_config/config.php');
include('../templates/header.inc');

$errMessage = NULL;
$mailMessage = NULL;

if(isset($_POST['submit'])){
  if(!empty($_POST['name']) && preg_match("/^[a-zA-Z]+([ a-zA-Z-]+)*$/i", $_POST['name'])){
      $name = $_POST['name'];
      $n = TRUE;
  }

  else{
      $errMessage .= "Please enter your name!<br />\n";
  }

  if(!empty($_POST['address1']) && preg_match("/^[0-9a-zA-Z\.\-\ ]+$/i", $_POST['address1'])){
      $address1 = $_POST['address1'];
      $a1 = TRUE;
  }

  else{
      $errMessage .= "Please enter your address!<br />\n";
  }

  if(!empty($_POST['address2']) && preg_match("/^[0-9a-zA-Z\.\-\ ]+$/i", $_POST['address2'])){
      $address2 = $_POST['address2'];
  }

  else{
      $address2 = '';
  }

  if(!empty($_POST['city']) && preg_match("/^[a-zA-Z\.\-\ ]+$/i", $_POST['city'])){
      $city = $_POST['city'];
      $c = TRUE;
  }

  else{
      $errMessage .= "Please enter your city!<br />\n";
  }

  if(!empty($_POST['state']) && preg_match("/^[a-zA-Z]{2}$/i", $_POST['state'])){
      $state = $_POST['state'];
      $s = TRUE;
  }

  else{
      $errMessage .= "Please enter your state!<br />\n";
  }

  if(!empty($_POST['zipcode']) && preg_match("/^[0-9]{5}([\-0-9]{4})?$/i", $_POST['zipcode'])){
      $zipcode = $_POST['zipcode'];
      $z = TRUE;
  }

  else{
      $errMessage .= "Please enter your zipcode!<br />\n";
  }

  if($n && $a1 && $c && $s && $z){
      $mailMessage .= "$name\n$address1\n$address2\n$city, $state $zipcode\n\n$myCart";
      mail('[email protected]', 'Test message', $mailMessage);
      echo "Your mail has been sent, $name<br />\n";
  }

  else{
      echo "<div style='color: red;'>$errMessage</div>\n";
  }
}

?>

<form name="checkout" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
  Name: <input type="text" name="name" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" /><br />
  Address 1: <input type="text" name="address1" value="<?php if(isset($_POST['address1'])) echo $_POST['address1']; ?>" /><br />
  Address 2: <input type="text" name="address2" value="<?php if(isset($_POST['address2'])) echo $_POST['address2']; ?>" /><br />
  City: <input type="text" name="city" value="<?php if(isset($_POST['city'])) echo $_POST['city']; ?>" /><br />
  State: <input type="text" name="state" value="<?php if(isset($_POST['state'])) echo $_POST['state']; ?>" /><br />
  Zipcode: <input type="text" name="zipcode" value="<?php if(isset($_POST['zipcode'])) echo $_POST['zipcode']; ?>" /><br />
  <input type="submit" name="submit" value="Checkout" />
</form>

<?php

$_SESSION['myCart'] = NULL;
$_SESSION['ip'] = urlencode(serialize($ip));

ob_end_flush();

?>
[/code]

I'm thinking that the error may have something to do with the cart calling getTotal on itself...my syntax is probably wrong there.  Other than that, though, I'm at a loss as to why it's not working.  Please help.
Link to comment
https://forums.phpfreaks.com/topic/32591-problem-with-__tostring/
Share on other sites

Your __toString() seems OK. I took your ShoppingCart class, added a Product class and then tried outputting the cart.
[code]
<?php
class Product {
    private $name;
    private $qty;
    private $price;
   
    public function __construct ($n, $q, $p) {
        $this->name = $n;
        $this->qty = $q;
        $this->price = $p;
    }
   
    public function getName ()  {
        return $this->name;
    }
    public function getQuan ()  {
        return $this->qty;
    }
    public function getPrice ()  {
        return $this->price;
    }
}

class ShoppingCart{
  private $Cart = array();

  public function addProduct($name, $price, $quantity){
      $this -> Cart[] = new Product($name, $price, $quantity);
  }

  public function getTotal(){
      $total = 0;

      foreach($this -> Cart as $value){
        $total += $value -> getPrice();
      }

      return $total;
  }

  public function __toString(){
      $message = NULL;
      $message .= "Name:\tQty\tPrice:\n";

      foreach($this -> Cart as $value){
        $message .= "{$value->getName()}\t{$value->getQuan()}\t{$value->getPrice()}\n";
      }

      $message .= "\t\t--------\nTotal:\t\t{$this->getTotal()}";
      return $message;
  }
}

$kart = new ShoppingCart;
$kart->addProduct ('a', 1, 5);
$kart->addProduct ('b', 1, 15);
$kart->addProduct ('c', 2, 8);

echo '<pre>';
echo $kart;
echo '</pre>';

?>
[/code]

This gave -->
[pre]
Name: Qty Price:
a 1 5
b 1 15
c 2 8
--------
Total: 28
[/pre]

EDIT : from the manual

It is worth noting that the __toString method will only be called when it is directly combined with echo() or print().

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.