Object Oriented Programming (OOP) Concept with Coding Example and Simplicity
Categories - Laravel PHP Framework PHP Tags - PHP Laravel   Maniruzzaman Akash   3 years ago   3076   4 minutes   0

Object Oriented Programming (OOP) Concept with Coding Example and Simplicity

Object Oriented Programming (OOP) Concept with Coding Example and Simplicity

 

Today, I'll discuss about OOP Concept for any programming language.

Object Orietented Programming has 5 most important feature, that we need to know and focus before starting to learn OOP in depth.

  1. Class and Object or Instantiation
  2. Inheritance 
  3. Polymorphism 
  4. Encapsulation 
  5. Abstraction 

Ok, let's discuss about those parts of OOP. I'll focus on simplicity to understand the concepts.

Language - PHP

 

1) Class

Class is one kind of custom data type and the blue print of any object. In class we can define some variable and methods of that object.

Variables are the property and methods are the function of that class.

 

Ex 01. of a Class Using PHP

class User {
  public $name = "";
  public $username = "";
  private $password = "";

  function __construct($name, $username, $password){
      $this->name =  $name;
      $this->username =  $username;
      $this->password =  $password;
  }

  public function getPassword(): string{
    return $this->password;
  }

  public function setPassword($password): void{
    $this->password = $password;
  }

  public function printUserName(): string{
    echo $this->username;
  }
}

Demonstration - Here is a basic User class, which has 3 member variables and 3 functions/methods.

 

1.1) Object

Object are the instance of a class. It is the instantiation of a class with accessing all of it’s properties and methods.

 

Ex 02 of Object in PHP

$user = new User("Jhon Doe", "jhon", "jhon@123");

// Now can access any public variables and methods of the class using this object.
$user->printUserName(); // output: jhon

$user->getPassword(); // output: jhon@123
$user->setPassword("UpdatedPasswordJhon");
$user->getPassword(); // output:UpdatedPasswordJhon

 

2) Inheretance:

Inheritance is one of the key principle of OOP concept. In a situation, when we need to create new classes and need to access some common things in the classes, then we create a parent class of combining of all it's common properties and methods. And create a child class which inherit everything of parent class, is the inheritance of OOP.

 

Ex 03. 

Let assume from top, we have a User class defined at Ex 01. We have 3 types of User.

  • Student
  • Teacher
  • Admin

 

And think these new classes also should have the User class properties and methods.

So, in these scenario, User is the parent class and Student, Teacher and Admin are the child classes.

 

class Student extends User{
  public $semester1Mark = 50;
  public $semester2Mark = 70;

  public function getCGPA(){
    // Do the CGPA calculation logic here
  }
}

$student = new Student("Akash", "akash", "akash@1234");
$student->getCGPA();

// also access parent class properties and methods
$student->getPassword(); // akash@1234

 

3) Polymorphism:

Polymorphism  means many shapes. It's  a key principle of OOP concept.In a nutshell, we can call it Overloading.

 

Let me explain the scenario, when it happens. We come polymorphism means, we have done the inheritance part. 

Now, assume in child classes, we need to call same function and do different jobs based on different number and types of parameter.

That means, we can call a method with different number of parameters and it'll 

do different work in different methods.

It's actually called Method Overloading.

See examples to clarify.

 

Ex 04.

 in Java Method Overloading

public class Shape
{
	public static void main(String[] args) {
		System.out.println(area(2));     // For radius - 6.282
		System.out.println(area(4, 5));  // For rectangle - 20.0 
	}
	
	public static double area(int r){
            return 3.1416 * r;
        }
    
        public static double area(double width, double height){
            return width * height;
        }
}

Look, there is same function area() is written twice. It could be written any number of times, just changable of number of arguments.

 

In PHP, magic method __call() is used to achieve this - 

class Shape {
      const PI = 3.142 ;
      function __call($name,$arg){
         if($name == 'area')
            switch(count($arg)){
               case 0 : return 0 ;
               case 1 : return self::PI * $arg[0] ;
               case 2 : return $arg[0] * $arg[1];
            }
      }
   }
   $circle = new Shape();
   echo $circle->area(3);
   $rect = new Shape();
   echo $rect->area(8,6);

 

4) Encapsulation:

To secure any variable or methods, in OOP, there is a term called encapsulation. We can create access modifier to access any variable outside of the class, which is called Encapsulation.

 

Look at our Ex 01, here we've created a password variable which is only accessable on that class, not outside of that class. By that we're ensuring to secure our password. If that needs to change or retreive, we rather call another functions, like getPassword() and setPassword()

$user = new User("Akash", "akash", "123456");
echo $user->getPassword();
echo " ";
echo $user->password; // Fatal Error: Cannot access private property User::$password

 

 5) Abstruction:

Abstruction is one of key concept of Object Oriented Programming Languages.

In OOP, abstruction means, hiding unncessary data and shows only the relevant data set and reuse that dataset accross the multiple classes.

 

Like to create an Employee Bank information's of User Class,

class User{
  public $name = "";
  public $address = "";
  public $phone_no = "";
  public $favorite_movie = "";
  public $favorite_music= "";
  public $favorite_food = "";
}

// Bank User class
class BankUser extends User{
  // Issue because, not needed the unncessary $favorite_movie, $favorite_music, $favorite_food variables.
}

 

So, create a real reliable and reusable user class - 

abstruct class User{
  public $name = "";
  public $address = "";
  public $phone_no = "";

  abstruct public function getFullAddress() : string{}
}

// Bank User class
class BankUser extends User{
  // ok
}

class StudentUser extends User{
  // ok
}

class HospitalUser extends User{
  // ok
}

 

Roles of abstruct class

  1. Must have abstruct method in the class which is also called abstruct class.
  2. Abstruct method must not be initilialized. Only declaration, no need to define, Defination will be in object.
  3. Number if required arguments should hasve same.

 

 

 

Previous
PHP If-else-elseif and Switch-case
Next
PHP String Functions - All necessary String functions in PHP to manage strings better.