fork download
  1. <?php
  2.  
  3. abstract class Book
  4. {
  5. // public $format = ['HARD', 'POCKET'];
  6. protected $_price;
  7.  
  8. public function __construct($price)
  9. {
  10. $this->_price = setPrice($price);
  11. }
  12.  
  13. public function setPrice($price)
  14. {
  15. if ($price > 0) {
  16. $this->_price= $price;
  17. } else {
  18. throw new Exception("Price cannot be less than 0");
  19. }
  20. }
  21.  
  22. public function getPrice()
  23. {
  24. return $this->_price;
  25. }
  26.  
  27.  
  28. }
  29.  
  30. class Hard extends Book
  31. {
  32.  
  33. public function __construct($price){
  34. $this->setPrice($price);
  35. }
  36.  
  37. public function setPrice($price){
  38. $this->_price= $price+ $price * 1/4;
  39. }
  40. }
  41.  
  42. class Pocket extends Book
  43. {
  44. public function __construct($price){
  45. $this->setPrice($price);
  46. }
  47.  
  48. }
  49. class BookFactory
  50. {
  51.  
  52. public static function add($format, $price){
  53. $format = ucwords($format);
  54. if(class_exists($format)) {
  55. return new $format($price);
  56. } else {
  57. throw new Exception('Format not supported.');
  58. }
  59. }
  60.  
  61. }
  62.  
  63. $book1 = BookFactory::add('HARD',600);
  64. echo "The " . get_class($book1) . " is \${$book1->getPrice()}";
  65. echo "\r\n";
  66. $book2 = BookFactory::add('pocket',600);
  67. echo "The " . get_class($book2) . " is \${$book2->getPrice()}";
Success #stdin #stdout 0.02s 82560KB
stdin
Standard input is empty
stdout
The Hard is $750
The Pocket is $600