Posted By

koncept on 12/27/09


Tagged

class method php5 example chaining


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

nfreear


PHP5 Method Chaining Example


 / Published in: PHP
 

Dead salesman, BILLY MAYS, age(50) sold the following products:

  • Awesome Auger
  • Big City Slider
  • Dash Tray
  • Hercules Hook
  • Mighty Mendit
  1. <?php
  2. class DeadObnoxiousInfomercialSalesman {
  3. protected $name = "Anonymous Salesman";
  4. protected $age = "unknown";
  5. protected $products = array();
  6. public function name($name){
  7. $this->name = $name;
  8. return $this;
  9. }
  10. public function age($age){
  11. $this->age = $age;
  12. return $this;
  13. }
  14. public function sold($product){
  15. $this->products[] = $product;
  16. return $this;
  17. }
  18. public function __toString(){
  19. $out = sprintf("Dead salesman, %s, age(%s)", $this->name, $this->age);
  20. if($this->products){
  21. sort($this->products);
  22. $out .= sprintf(
  23. " sold the following products:\n%s",
  24. " - ".join("\n - ",$this->products)
  25. );
  26. }
  27. return $out;
  28. }
  29. }
  30.  
  31. $person = new DeadObnoxiousInfomercialSalesman();
  32.  
  33. echo $person ->name("BILLY MAYS")
  34. ->age(50)
  35. ->sold("Awesome Auger")
  36. ->sold("Big City Slider")
  37. ->sold("Dash Tray")
  38. ->sold("Hercules Hook")
  39. ->sold("Mighty Mendit");
  40. ?>

Report this snippet  

You need to login to post a comment.