PHP - Adding method to Truck object

Introduction

The following code shows how to add method to class and access the its own properties.

Demo

<?php
       class Truck {
         public $color;
         public $manufacturer;
         public $model;
         private $_speed = 0;

         public function accelerate() {
           if ($this->_speed  >= 100) return false;
           $this->_speed += 10;/*  w  w  w .  j  a v a  2 s .c  o m*/
           return true;
         }

         public function brake() {
           if ($this->_speed  <= 0) return false;
           $this->_speed -= 10;
           return true;
         }

         public function getSpeed() {
           return $this->_speed;
         }

        }

       $myTruck = new Truck();
       $myTruck->color ="red";
       $myTruck->manufacturer ="Niu";
       $myTruck->model ="usa";

       echo "I'm driving a $myTruck->color $myTruck->manufacturer $myTruck->model";
       while ($myTruck->accelerate()) {
         echo"Current speed:". $myTruck->getSpeed()."mph \n";
       }
       while ($myTruck->brake()) {
             echo"Current speed:". $myTruck->getSpeed()."mph \n";
       }
?>

Result

Related Topic