php
PHP - Object Oriented Programming (OOPs)
Object-oriented programming (OOP) was first introduced in php4. Now-a-days Java and C++ are mostly used for object-oriented programming. The major concept of the object oriented programming in PHP is introduced from version 5(we commonly known as php5). But still, in the php5 object model is designed nicely. If you have the good understanding of OOP then you can create a very good architecture of your PHP application. You only need to know some of the basic principles of object-oriented programming and how to implement that concept of oop in PHP. In whole series I will use abbreviation OOP for Object Oriented Programming.

The  Object Oriented concepts in PHP are:

  • Class 
  • Objects
  • Inheritance
  • Interface
  • Polymorphism 
  • Overridning
  • Encapsulation 
  • Constructor 
  • Destructor
  • Abstraction
Create a class & Object

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

A class defines constituent members which enable class instances to have state and behavior. Data field members enable a class object to maintain state and methods enable a class object's behavior.

A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$.

A class may contain its own constants, variables (called "properties"), and functions (called "methods").

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Create a class</title>
</head>
<body>

<?php
	class Books{
	  public function name(){
	  echo 'PHP Books is : ';
	  }
	  public function price(){
	  echo ' <b>750 Rs/-</b>';
	  }
	}
	$obj = new Books();
	$obj->name();
	$obj->price();
?>

</body>
</html>
Output :
Creating Objects in PHP

An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.

When class is created, we can create any number of objects to that class. The object is created with the help of new keyword.

Calling Member Functions

The calling member function defined inside a class and are used to access object data.

When the object is created we can access the variables and method function of the class with the help of operator ->, accessing the method is done to get the information of that method. Also look into how we can access object properties via variables

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Calling Member Functions</title>
</head>
<body>

<?php
   class Books {
      /* Member variables */
      var $price;
      var $title;
      /* Member functions */
      function setPrice($my_pri){
         $this->price = $my_pri;
      }
      function getPrice(){
         echo $this->price ."<br/>";
      }
      function setName($my_pri){
         $this->title = $my_pri;
      }
      function getName(){
         echo $this->title ." <br/>";
      }
    }
	$HTML5 = new Books();
	$CSS3 = new Books();
	$php = new Books();
	$HTML5->setName( "HTML5" );
	$php->setName( 'PHP' );
	$CSS3->setName( 'CSS3' );
	$HTML5->setPrice( 120 );
	$php->setPrice( 750);
	$CSS3->setPrice( 480 );
	
	$HTML5->getName();
	$php->getName();
	$CSS3->getName();
	$HTML5->getPrice();
	$php->getPrice();
	$CSS3->getPrice();
?>

</body>
</html>
Output :
Inheritance

Inheritance is concerned with the relationship between classes. The relationship takes the form of a parent and child. The child uses the methods defined in the parent class. The main purpose of inheritance is Re-usability– a number of children, can inherit from the same parent. This is very useful when we have to provide common functionality such as adding, updating and deleting data from the database.

Types Of Inheritance

  • Single Level Inheritance
  • Multilevel Inheritance

Single Level Inheritance : In Single Level Inheritance the Parent class methods will be extended by the child class. All the methods can be inherited.

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Single Level Inheritance</title>
</head>
<body>

<?php
	class A {
		public function printItem($string) {
			echo ' Hi : ' . $string; 
		} 
		public function printPHP() {
			echo 'I am from Nellore' . PHP_EOL;
		}
	}
	class B extends A {
		public function printItem($string) {
			echo 'Hi: ' . $string . PHP_EOL;
		}
	 public function printPHP() {
			echo "I am from Gudur";
		}
	}
	$a = new A();
	$b = new B();
	$a->printItem('V V R Reddy ');
	$a->printPHP();
	echo "<br />" ;     
	$b->printItem('V R Reddy '); 
	$b->printPHP();       
?>

</body>
</html>
Output :

MultiLevel Inheritance : In MultiLevel Inheritance, the parent class method will be inherited by child class and again subclass will inherit the child class method.

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Multi Level Inheritance</title>
</head>
<body>

<?php
	class A {
		public function my_age() {
		return  '27';
		}
	}
	class B extends A {	
		public function mywife_age() {
		return  ' 26';
		}
	}
	class C extends B {
		public function mymother_age() {
		return  '51';
		   }
			public function myHistory() {
			echo "My age is : " .$this->my_age();
			echo "<br />";
			echo "My wife age is : ".$this-> mywife_age();
			echo "<br />";
			echo "My mother age is : " . $this->mymother_age();
			}
	}
	$obj = new C();
	$obj->myHistory();
?>

</body>
</html>
Output :
INTERFACES

An interface is a description of the actions that an object can do. Interface is written in the same way as the class the declaration with interface keyword.

All methods are declared in an interface must be public; this is the nature of an interface. The interface must be implemented within a class; failure to do so will result in a fatal error.

The class implementing the interface must use the exact same method signatures as are defined in the interface.

Interfaces can be extended like classes using the extends operator.

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - INTERFACES</title>
</head>
<body>

<?php
interface A {
    public function Addition();
}
interface B extends A {
    public function Divide();
}
interface C extends B {
    public function Multiplication();
}
class D implements C {
    
    public function Addition() {
        $a=9;
        $b=18;
        $c=$a+$b;
        echo "Addition of 9+18 is : " . $c;
    }
	public function Divide() {
		$var=27;
		$var1=3;
		$var3=$var/$var1;
		echo "Division of 27/3 is : " . $var3;
	}
	public function Multiplication() {
        $x=9;
        $y=5;
        $z=$x*$y;
        echo "Multiplication of 9*5 is : " . $z;
    }
}
$obj = new D();
$obj->Addition();
echo "<br />";
$obj->Divide();
echo "<br />";
$obj->Multiplication();
?>

</body>
</html>
Output :
Polymorphism
This is an object oriented concept where same function can be used for different purposes. The main purpose of polymorphism is Simplify maintaining applications and making them more extendable. For example function name will remain same but it make take different number of arguments and can do different task.
Function Overriding

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return some values.

<?php
	function getPrice() {
	   echo $this->price . "<br/>";
	   return $this->price;
	}
	   
	function getTitle(){
	   echo $this->title . "<br/>";
	   return $this->title;
	}
?>
Encapsulation
This is concerned with hiding the implementation details and only exposing the methods. The encapsulation concept are we encapsulate all the data and member functions together to form an object.

The main purpose of encapsulation is to :

  • Reduce software development complexity : By hiding the implementation details and only exposing the operations, using a class becomes easy.
  • Protect the internal state of an object : Access to the class variables is via methods such as get and set, this makes the class flexible and easy to maintain.

The internal implementation of the class can be changed without worrying about breaking the code that uses the class.

Constructors and Destructors

Constructor Functions are special type of functions which are called automatically whenever an object is created. The constructor is a special built-in method, added with PHP 5, allows developers to declare for classes. Constructors allow to initializing object properties ( i.e. the values of properties) when an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.

PHP constructor method __construct() (known as constructor) is executed automatically whenever a new object is created. Similarly, the magic method __destruct() (known as destructor) is executed automatically when the object is destroyed. A destructor function cleans up any resources allocated to an object once the object is destroyed.

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Constructors and Destructors</title>
</head>
<body>

<?php
	class Construct_Destruct
	{
		// Constructor
		public function __construct(){
		  echo 'The class "' . __CLASS__ . '" was initiated..! <br />';
		}
		// Destructor
		public function __destruct(){
		  echo 'The class "' . __CLASS__ . '" was destroyed..! <br />';
		}
	}	 
	// Create a new object
	$obj = new Construct_Destruct;
	 
	// Output a message at the end of the file
	echo "The end of the file is reached. <br />";
?>

</body>
</html>
Output :

A destructor is called automatically when a scripts ends. However, to explicitly trigger the destructor, you can destroy the object using the PHP unset() function, as follow :

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Constructors and Destructors</title>
</head>
<body>

<?php
	class Construct_Destruct
	{
		// Constructor
		public function __construct(){
			echo 'The class "' . __CLASS__ . '" was initiated ...!<br />';
		}
		
		// Destructor
		public function __destruct(){
		echo 'The class "' . __CLASS__ . '" was destroyed...!<br />';
		}
	}
	 
	// Create a new object
	$obj = new Construct_Destruct;
	 
	// Destroy the object
	unset($obj);
	 
	// Output a message at the end of the file
	echo "The end of the file is reached.<br>";
?>

</body>
</html>
Output :
Abstract Classes

An abstract class is a class that contains at least one abstract method. The abstract method is function declaration without anybody and it has the only name of the method and its parameters.

There can be any number of methods in the class and we have to declare the class as abstract only when there is an abstract method

<!DOCTYPE html>
<html>
<head>
    <title>PHP OOPs - Abstract class</title>
</head>
<body>

<?php
	abstract class Books {
		public abstract function getBookName();
		public abstract function getPrice();
	}
	class Php  extends Books {
		public function getBookName() {
			return "PHP Book : ";
		}
		public  function getPrice() {
		  return 750 . '<br/>';
		}
	}
	class MySQL extends Books {
		public function getBookName() {
			return "MySQL Book : ";
		}
		public function getPrice() {
			return 320 . '<br/>';
		}
	}
	$Book = new Php();
	$Books = new MySQL();
	echo $Book->getBookName();
	echo $Book->getPrice();
	echo $Books->getBookName();
	echo $Books->getPrice();
?>

</body>
</html>
Output :

The Objects cannot be created for the abstract classes. If the abstract method is defined as protected in the parent class, the function implementation must be defined as either protected or public, but not private.

Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).