Advertisement
eimkasp

PHP OOP extends example

Nov 10th, 2016
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.37 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4.  
  5.  
  6. // The parent class has hello method that returns "beep".
  7. class Car {
  8.  
  9.  //A private property or method can be used only by the parent.
  10.   private $model;
  11.   private $price;
  12.  
  13.     public function __construct() {
  14.         echo "construct car";
  15.     }
  16.  
  17.  
  18.  
  19.   public function hello()
  20.   {
  21.     return "beep";
  22.   }
  23.  
  24.    public function setModel($model)
  25.     {
  26.         $this ->model = $model;
  27.     }
  28.    
  29.     public function getModel()
  30.     {
  31.         return $this ->model;
  32.     }
  33.  
  34.     public function setPrice($price)
  35.     {
  36.         $this->price = $price;
  37.     }
  38.    
  39.     public function getPrice()
  40.     {
  41.         return $this ->price;
  42.     }
  43.  
  44. }
  45.  
  46. //The child class has hello method that returns "Halllo"
  47. class SportsCar extends Car {
  48.  
  49.     public function __construct() {
  50.         parent::__construct();
  51.     }
  52.     public function raceMode() {
  53.         $this->price += 3000;    
  54.     }
  55. }
  56.  
  57. //The child class has hello method that returns "Halllo"
  58. class FamilyCar extends Car {
  59.    
  60. }
  61.    
  62. //Create a new object
  63. $sportsCar1 = new SportsCar();
  64.  
  65. //Get the result of the hello method
  66. $sportsCar1->setModel("Fiat 500");
  67. $sportsCar1->setPrice(5000);
  68. $sportsCar1->raceMode();
  69. echo $sportsCar1->getModel();
  70.  
  71.  
  72. $familyCar1 = new FamilyCar();
  73.  
  74. //Get the result of the hello method
  75. $familyCar1->setModel("Fiat multipla");
  76. $familyCar1->setPrice(1000);
  77.  
  78. echo $familyCar1->getModel();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement