Skip to main content

OOP concept in php

Abstraction

Abstraction is the key concept in OOP language.

Its main goal is to handle the complexity by hiding the unnecessary details from the user.

What does it mean.

We drive car? Yes. For driving car is we need to know how engine works, how gear box works and how music system work?

No, because these are very complex things to understand. It the mechanical engineer/ technician duty to deal with them.

For end-user perspective user/driver have to focus on how to drive car / How to shift gear and how to play music using control panel.

Now come in programming/coding terminology

It is high level representation of  object and concept of what is doing rather than how it doing.

In simple words abstraction help you create a simpler and easy representation of  something complex. 

Let say we want to build system to manage different types of vahicle

Now all vahicle a have some common characteristics like branding, manufacturer and also have specific characteristics, properties, behavour mean startEngine() mechanism for car, Bus, motorbike is different from each other.

Let see code example:

abstract class Vehicle {

    protected $brand;

    protected $year;


    public function __construct($brand, $year) {

        $this->brand = $brand;

        $this->year = $year;

    }


    abstract public function start();

    abstract public function stop();


    public function getInfo() {

        return "Brand: {$this->brand}, Year: {$this->year}";

    }

}


class Car extends Vehicle {

    public function start() {

        return "Car started";

    }


    public function stop() {

        return "Car stopped";

    }

}


class Motorcycle extends Vehicle {

    public function start() {

        return "Motorcycle started";

    }


    public function stop() {

        return "Motorcycle stopped";

    }

}


class Truck extends Vehicle {

    public function start() {

        return "Truck started";

    }


    public function stop() {

        return "Truck stopped";

    }

}

$car = new Car('Toyota', 2023);

echo $car->getInfo(); // Output: Brand: Toyota, Year: 2023

echo $car->start();   // Output: Car started

getInfo() method use to retrieve the common information for all vehicles.

Now one more important concept what is concrete classes?

Answer:

Subclasses are concrete classes. really how?

Those classes which inherit the properties and method of its parent class. called concrete classes.

What does it mean: Class which implement the methods of parent abstract class according its need/requirement this class is act as concrete class.

From above example car, motorcycle, truck are concrete classes.

Polymorphism

Polymorphism mean the object have ability to adopt multiple forms / shaps / behavour.

Example: Let say a man can be at the same time a husband, father, employee.

Similarly in classes.

A same name method can be act/perform different task based on different numbers and types of argument it is receiving.

Below is the simple example, see both class man and person have same nature method but when you create / initiate class with instant you also pass the required argument to the class constructor.

Note: But when you are think defining of function in classes with different arguments, PHP give you an error of method must be match with abstract class human::nature().

public function nature();

public function nature(arg1);

public function nature(arg1,arg2);

Code Example:

<?php

abstract class human{

abstract public function nature();

}

class man extends human{

    public $name;

    public $nature;

    public function __construct($nature){

    $this->nature = $nature;

    }

    public function callName(){

    echo "Man Class Name";

    }

    public function callAge(){

    echo "Man Class Age:20";

    }

    public function nature(){

    echo "man human nature is ".$this->nature;

    }

}


class person extends human {

public $name;

    public function callName(){

    echo "Person Class Name";

    }

    public function callAge($age){

    echo "Person Class Age:".$age;

    }

    public function nature(){

    echo "person human nature is good";

    }

    

}


$obj_man = new man('bad');

$obj_person = new person();

echo "<br>";

echo "abstract class exampe";

echo "<br>";

echo $obj_person->nature();

echo "<br>";

echo $obj_man->nature();


?>

There are two types of polymorphism

1) Compile time polymorphism (Static, early binding).

2) Runtime polymorphism (dynamic, late binding).

1. Compile Time Polymorphism

This type of polymorphism offer function overloading operation.

What is function overloading:

When there are multiple function with same name but different number and type of arguments in the same class use to perform different task. called overloading mechanism.

But PHP doesn't support function overloading because it give error of same declaration of method but still there is a way in which based on argument passed to function we call different function.

Example code of function overloading in PHP

class MathOperations {

    public function calculate() {

        $numArgs = func_num_args();

        $args = func_get_args();


        if ($numArgs === 2) {

            return $this->calculateTwoArgs($args[0], $args[1]);

        } elseif ($numArgs === 3) {

            return $this->calculateThreeArgs($args[0], $args[1], $args[2]);

        } else {

            throw new InvalidArgumentException("Invalid number of arguments provided.");

        }

    }


    private function calculateTwoArgs($a, $b) {

        return $a + $b;

    }


    private function calculateThreeArgs($a, $b, $c) {

        return $a + $b + $c;

    }

}


$math = new MathOperations();


// Using the calculate() method with different numbers of arguments

echo $math->calculate(2, 3);         // Output: 5

echo $math->calculate(2, 3, 4);      // Output: 9

2. Runtime Polymorphism

Runtime polymorphism refers to process when a call to overridden process is resolved at run time.

Function overriding:

Function overriding occurs when subclass define same method as a method exactly in parent class also have.

Code Example

class Animal { public function makeSound() { echo "Generic animal sound\n"; } } class Dog extends Animal { public function makeSound() { echo "Woof! Woof!\n"; } } class Cat extends Animal { public function makeSound() { echo "Meow!\n"; } } // Creating objects of child classes $dog = new Dog(); $cat = new Cat(); // Calling overridden methods $dog->makeSound(); // Output: Woof! Woof! $cat->makeSound(); // Output: Meow!


Comments

Popular posts from this blog

Install MariaDB Latest Version 11.4 in Red Hat Version 9

 This this post i will show you step by step the installation process of mariaDB in red hat version 9. Step1 Run the command to pull the latest updated packages on applications installed in your system. -dnf update If you get Kernal update than reboot the system -reboot Step2 Go to official mariaDB site Make mariadb repository in /etc/yum.repos.d Place the configuration in this file # MariaDB 11.4 RedHatEnterpriseLinux repository list - created 2024-09-24 11:12 UTC # https://mariadb.org/download/ [mariadb] name = MariaDB # rpm.mariadb.org is a dynamic mirror if your preferred mirror goes offline. See https://mariadb.org/mirrorbits/ for details. # baseurl = https://rpm.mariadb.org/11.4/rhel/$releasever/$basearch baseurl = https://mirrors.aliyun.com/mariadb/yum/11.4/rhel/$releasever/$basearch # gpgkey = https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB gpgkey = https://mirrors.aliyun.com/mariadb/yum/RPM-GPG-KEY-MariaDB gpgcheck = 1 Now install the mariaDB with its dependencies package...

Car Company website Proposal Document.

 Car Company Website Proposal Document. What this website offers and give value to company and its customers. This site will showcase the products (vehicles) with simple and sleek design. It will show high impact vehicles images. The specification of vehicle which user can easily understand and make comparisons.  Features of this website both Front-End and Back-End side. Front-End Features 1. Landing page of website 1.1 This page will display classy look of the web design by showcasing different vehicle high resolution images. 1.2 Overview of all Services the company offering to their valuable customers 1.3 Testimonials Client feedback on your services and satisfaction with vehicle which build long term value to company and customer relationship. 1.4 Window Pop-up for showing  sales and events or any news. 2. Pages on this website 2.1 Services Page This page will demonstrate number of Maintenance Services of vehicles this company offers. Now there are two types of service...

React js Commands

Navigation   1. Install React Router Dom npm install react-router-dom npm install react-router-dom@6