Object Oriented Programming Basic Guide for Beginners

Follow by Email
Facebook
Google+
http://xtremepassion.leladystore.com/2019/01/object-oriented-programming-basic-guide-for-beginners/
YouTube
PINTEREST
INSTAGRAM

A VARIABLE REPRESENT BY A SINGLE DATA TYPES
Often in coding, we had been taught to represent each variable with a single data types for say,
Numeric numbers represent by integer data types,
Text or characters represent by string data types,
True or False represent by boolean data types and so on so forth in the program.

REAL WORLD ENTITY REPRESENT BY CUSTOM DATA TYPES
What about the real world entity such as book? car? and etc that can’t be represented by a single data types in programming. This is when object-oriented come in place introduced class and object whereby we can create our own custom data types for the class. Examples,
Book Class have Title, Author, and Pages attributes or data types;
Car Class have Manufacturer, Model, and Color attributes or data types.


Figure1: Classes and Objects

CODING: CREATE BOOK CLASS WITH CONSTRUCTOR FUNCTION
First, create Book Class and define 3 attributes that describe the actual book. Then, create the Constructor function whereby it will be executed each time an object been created. With constructor function, it reduce lines of codes needed when object been created.

<?php
/**
 *=-----------------------------------------------------------=
 * Filename: bookClass.php
 *=-----------------------------------------------------------=
 * Author: LJLEE
 * Modified on: 28 Jan 2019
 *
 */

/**
 * Class is a blueprint for book.
 */   
  class Book {
    
    /*
     * Define custom data types for a book.
     * Define attributes or data types that represent a book.
     */     
    public $title;
    public $author;
    public $published;

    /*
     * Constructor function to be executed whenever new book object been created.
     * The purpose of having the constructor function is to reduce lines of
     * codes.
     */
    function __construct($title, $author, $published) {
      $this->title = $title;
      $this->author = $author;
      $this->published = $published;
    }

  }

?>

CREATE BOOK’S OBJECT AND DISPLAY EACH OBJECT’S DATA
After define Class (refer filename: bookClass.php), include the file in main program (refer filename: bookMain.php, eg: include ‘bookClass.php’;) so that main program able to use the class and function from bookClass. Then, create 2 new book objects and try to output each object’s value.

<?php
/**
 *=-----------------------------------------------------------=
 * Filename: bookMain.php
 *=-----------------------------------------------------------=
 * Author: LJLEE
 * Modified on: 28 Jan 2019
 *
 */
include 'bookClass.php';

      /* Create a Book object.
       * Create an instance of a class.
       * Create an actual Book.
       * Whenever Book object been created, constructor function to be executed
       *
       * If without constructor function, refer to below 4 lines of code just
       * to create a book object:-
       * $bookA = new Book();
       * $bookA->title = "Anne of Green Gables";
       * $bookA->author = "L. M. Montgomery";
       * $bookA->published = 1908;
       * In facts, we can create a book object with just a line as shown below.
       */
       $book1 = new Book("Anne of Green Gables", "L. M. Montgomery", 1908);
       $book2 = new Book("The Da Vinci Code", "Dan Brown", 2003);

       //Display the title from book1
       echo $book1->title;
       //Line break 
       echo "<br/>";
       //Display the author from book2
       echo $book2->author;

?>

Output:
Anne of Green Gables
Dan Brown

VERIFY CONSTRUCTOR FUNCTION EXECUTION WHENEVER OBJECT GET CREATED
Refer to sample code below in verifying Constructor function to be executed whenever new book object been created. Noticed that each time new book() object been created, the program will run through the constructor function to output “book object been created”.

<?php
/**
 *=-----------------------------------------------------------=
 * Filename: bookClassVerify.php
 *=-----------------------------------------------------------=
 * Author: LJLEE
 * Modified on: 28 Jan 2019
 *
 */
  class Book {

    public $title;
    public $author;
    public $published;

    function __construct() {
      echo "book object been created <br/>";
    }

  }

?>

<?php
/**
 *=-----------------------------------------------------------=
 * Filename: bookMainVerify.php
 *=-----------------------------------------------------------=
 * Author: LJLEE
 * Modified on: 28 Jan 2019
 *
 */
include 'bookClassVerify.php';

      //Create book1 object
      $book1 = new Book();
      //Create book2 object
      $book2 = new Book();

?>

Output:
book object been created
book object been created

PUBLIC AND PRIVATE MODIFIER
In real world, imagine Public modifier as public toilet that allow everyone to use and access whereas Private modifier is the toilet in the private companyA that only accessible by it’s own staffs within the companyA compound. So, how do public access to the private companyA’s toilet? Somehow, you may register through the companyA security post to grant access into the companyA compound 😛 .

Back to coding environment; Create Car Class with 1 attribute as private modifier (refer carClass.php, eg: $manufacturer define as the private data types) and the other 2 with Public modifier (refer carClass.php, eg: $model and $color define as the public data types). You can easily update and retrieve the Car’s model and color from the main program (refer carMain.php). However, it is restricted to update and retrieve the Car’s manufacturer unless access through Getters and Setters methods within the Car class (refer carClass.php, eg: getManufacturer() and setManufacturer()).

ENCAPSULATION WITH GETTER AND SETTER METHODS
Retrieve the private data types value through Getter method in Car class (refer carClass.php, eg: function getManufacturer()) while update the private data types value through the Setter method (refer carClass.php, eg: function setManufacturer($manufacturer)). Furthermore, you may done some data validation before update the private variable. This is the way to achieve encapsulation to make sure sensitive data is hidden from users.

INHERITANCE USING EXTENDS KEYWORDS
Example been given for class ElectricCar extends Car {…} (refer carClass.php, eg: class ElectricCar extends Car {…}), meaning the ElectricCar object been created can use or utilise all of the functions in the Car class. ElectricCar class may also have its own methods or functions (refer carClass.php, eg: function askSiri()). However, Car class or called as superclass or parent class unable to use the functions in the ElectricCar class.

OVERRIDING METHOD
ElectricCar class can override the Car class (superclass or parent class) functions within its own class. Example, within ElectricCar class, the carEngine() method (refer carClass.php, eg: function carEngine()) override the value from the same method in Car class.

<?php
/**
 *=-----------------------------------------------------------=
 * Filename: carClass.php
 *=-----------------------------------------------------------=
 * Author: LJLEE
 * Modified on: 28 Jan 2019
 *
 */
  
/*
 * Blueprint for Car.
 */
class Car {

    /*
     * Define custom data types for a car.
     *
     * Define Visibility Modifier for $manufacturer as Private to avoid
     * public access to make changes into this car class.
     */
    private $manufacturer;
    public $model;
    public $color;

    /*
     * Constructor function to be executed whenever new car object been created.
     *
     * Take notes that value pass into setManufacturer function
     * for verification before set the corrected value into $manufacturer.
     *
     * Furthermore, public is unable to access or change the value directly
     * outside of Car class.
     */
     function __construct($manufacturer, $model, $color) {
       $this->setManufacturer($manufacturer); // pass to function & set correct value
                                              // for manufacturer attributes
       $this->model = $model;
       $this->color = $color;
     }

     /*
      * Getters
      * Return the manufacturer value
      */
     function getManufacturer() {
       return $this->manufacturer;
     }

     /*
      * Setters
      * This program only allow 2 verified manufacturer: Honda & Toyota.
      * $manufacturer value to be set as unknown other than above mentioned.
      *
      * setManufacturer function will verify the manufacturer value before
      * assigned the value to $manufacturer attribute
      * to avoid unwanted data been inserted.
      *
      */
     function setManufacturer($manufacturer) {
       if ($manufacturer == "Honda" || $manufacturer == "Toyota" ||
          $manufacturer == "Tesla") {
         $this->manufacturer = $manufacturer;
       } else {
         $this->manufacturer = "Unknown";
       }
     }

     function carAccelerate() {
       return " to speed up <br/>";
     }

     function carBrakes() {
       return " to stop <br/>";
     }

     function carEngine() {
       return " engine runs on gasoline <br/>";
     }

}

  /*
   * ElectricCar extends all the function from car.
   * Meaning ElectricCar able to use all the functions from Car.
   *
   * However, Car unable to use the function from ElectricCar.
   *
   * ElectricCar can override Car's function
   */
  class ElectricCar extends Car {

    function askSiri() {
      return " ask Siri to make a phone call <br/>";
    }

    //Override Car function
    function carEngine() {
      return " engine runs on rechargeable batteries <br/>";
    }
  }

?>

Let’s include the carClass.php file in the main program and test to output the value.

<?php
/**
 *=-----------------------------------------------------------=
 * Filename: carMain.php
 *=-----------------------------------------------------------=
 * Author: LJLEE
 * Modified on: 28 Jan 2019
 *
 */
include 'carClass.php';

    /*
     * Create car1 object & purposely insert wrong car manufacturer other's than
     * Honda or Toyota to the $manufacture attributes that set as private
     * modifier
     */
    $car1 = new Car("Honda", "JAZZ", "Green");
    //Create car2 object
    $car2 = new Car("Nissan", "VIOS", "Blue");

    /*
     * echo $car2->manufacturer;
     * Above line of code will caught with an error due to manufacturer attributes
     * had been set as private modifier.
     * The correct way is to called the getter function
     */
     echo "Car2 manufacturer name: ".$car2->getManufacturer();  //Output unknown
                                                                //because Nissan not meet the
                                                                //if... conditions in setManufacture function.

     echo "<br/>";                                              //line break
     echo $car1->model . $car1->carEngine();                    //Output JAZZ engine runs on gasoline
     echo $car1->getManufacturer().$car1->carBrakes();          //Output Honda to stop
     echo $car2->model.$car2->carAccelerate();                  //Output VIOS to speed up

     /*
      * echo $car1->askSiri();
      * The above line of code will caught with an Error due to askSiri function is
      * within the ElectricCar class whereas $car1 is the instance of Car class.
      * $car1 is the Car object and not the ElectricCar object. Hence, $car1 object
      * unable to use the function within the ElectricCar class.
      */

     /*
      * Create car3 object
      *
      * extends keywords allow ElectricCar utilized all the functions within Car class.
      * It allowed to override the existing Car functions within it's own class.
      */
     $car3 = new ElectricCar("Tesla", "Model X", "White");
     echo $car3->getManufacturer() . $car3->carBrakes();        //Output Tesla to stop
     echo $car3->model . $car3->carEngine();                    //Output Model X engine runs on rechargeable batteries
     echo $car3->getManufacturer() . $car3->askSiri();          //Output Tesla ask Siri to make a phone call

?>

Output:
Car2 manufacturer name: Unknown
JAZZ engine runs on gasoline
Honda to stop
VIOS to speed up
Tesla to stop
Model X engine runs on rechargeable batteries
Tesla ask Siri to make a phone call

** HAPPY CODING **

Leave a Reply

Your email address will not be published. Required fields are marked *

137 views