Object Oriented Programming in PHP

Object Oriented Programming in PHP


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we will be discussing about OOPS in PHP.

We can imagine our suites made of various objects like televisions, tables, microwaves, fridges, kettles, mixers, blenders, and so on. In the same way there is an object oriented programming (oop) concept that assumes everything as an object and implements a software by using different objects.

Object Oriented Concepts

Before we go into details, let us first define the important terms related to OOP.

  • Class - A class in OOP is the defined data type. It includes local functions and also local data. A class can be thought of as a template for making many instances of the same kind of objects.
  • Object - An object in OOP is an individual instance of the data structure defined by a class. A class is defined just once, and then make many objects that belongs to it.
  • Member Variables - These are the variables which are defined inside of the class. This data will be invisible to the outside of the class and can be accessed via member functions. The variables are called attribute of the object once an object is created.
  • Member Functions - These are the functions which are defined inside a class are used to access object data.
  • Inheritance - When a class is defined through inheriting existing function of a parent class, it is called inheritance. Here child class will inherit all or few member functions and variables of the parent class.
  • Parent class - A class that is inherited by another class. This is also known as base class or super class.
  • Child class - This is a class that inherits from the parent class. This is also called sub class.
  • Polymorphism - This can be explained as object oriented concept where by the same function can be made use of for different purposes. For example function name will remain same but but it takes different arguments and can perform different tasks.
  • Overloading - This is a type of polymorphism in which some or all of the operators have different applications based on the types of their arguments. In a similar way, functions can be overloaded with different applications.
  • Data Abstraction - This can be simply described as any representation of a data in which the implementation details are hidden.
  • Encapsulation - It refers to a concept of encapsulating all data and member functions together to form an object.
  • Constructor - It refers to an exceptional type of function which will be automatically called whenever there is an object formation from class.
  • Destructor - It refers to an exceptional type of function which will be automatically callled whenever an object is deleted or even goes out of scope.


Defining PHP Classes

Defining PHP Classes

The general form for defining a new class in PHP is as follows -

<?php
   class phpClass {
      var $var1;
      var $var2 = "constant string";
      
      function myfunc ($arg1, $arg2) {
         [..]
      }
      [..]
   }
?>

The following is the description of each line -

  • The unique form class, then followed by the name of the class you want to define.
  • Set of braces enclosing any numbers of var declarations and function definitions.
  • Variable declarations starts with a special form var, and followed by a conventional $ variable name; they may as well have initial assignment to a constant value.
  • The function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example

The following below is an example which defines a class of books types -

<?php
   class Books {
      /* Member variables */
      var $price;
      var $title;
      
      /* Member functions */
      function setPrice($par){
         $this->price = $par;
      }
      
      function getPrice(){
         echo $this->price ."<br/>";
      }
      
      function setTitle($par){
         $this->title = $par;
      }
      
      function getTitle(){
         echo $this->title ." <br/>";
      }
   }
?>

The variable $this is a special variable and it refers to the same object ie.itself.


Creating Object in PHP

Creating Objects in PHP

Once your class is defined, you can create as many objects as you want of that class type.

Example

Following is an example of how to create an object by using the new operator -

$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Here we've created three objects and these objects are independent on each other and they will have their separate existence. Now lets look at how we can access the member function and process member variables.

Calling Member Functions

After creating your objects, you are going to be able to call member functions related to that object. A member function will be able to process the member variables of related object only.

Example

The below example shows how to set title and prices for the three books by calling the member functions -

$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now, you call another member function so as to get the values set in above example -

$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

Output

When the above code is executed, it will produce the following result -

PysicPysics for High School
Advanced Chemistry
Algebra
10
15
7


Constructor in PHP

Constructor Functions

Constructor are special types of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by utilizing a lot of things making use of constructor functions.

PHP provides a special function which is called _construct() to define a constructor. You can pass as many arguments as you like into the constructor function.

Example

The below example creates a constructor for Books class and it initializes price and title for the book at the time of the object creation.

function __construct( $par1, $par2 ) {
   $this->title = $par1;
   $this->price = $par2;
}

Now we do not need to call the set function separately to set the price and title. We can initialize these two member variable only at the time of object creation.

Example

Try the following example below for better understanding -

$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

Output

When the above code is executed, it will produce the following result -

Physics for High School
Advanced Chemistry
Algebra
10
15
7

Destructor in PHP

Destructor

Like constructor functions in PHP, you can also define a destructor function by using the _destruct() function. You can release all the resources within a destructor.


Inheritance

The PHP class definitions can optionally inherite from a parent class definition by making use of the extends clause.

Syntax

The syntax is as follows -

class Child extends Parent {
   <definition body>
}

The effect of inheritance is that the child class has the following characteristics -

  • Automatically has all of the member variable declaration of the parent class.
  • Automatically has all of the same member functions as the parent, which by default works the same manner as those functions do in parent class.

Example

The following example inherites Book class and adds more functionality to it based on the requirements -

class Novel extends Books {
   var $publisher;
   
   function setPublisher($par){
      $this->publisher = $par;
   }
   
   function getPublisher(){
      echo $this->publisher. "<br />";
   }
}

Now aside the functions that are inherited, the class Novel keeps two extra member functions.

Overriding in PHP

Function Overriding

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

Example

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

function getPrice() {
   echo $this->price . "<br/>";
   return $this->price;
}
   
function getTitle(){
   echo $this->title . "<br/>";
   return $this->title;
}

Public Member

Unless specified otherwise, properties and methods of a class are public. That is to say they may be accessed in three different situations.

  • From outside of the class in which it is declared.
  • From inside of the class in which it is declared.
  • From inside of another class that implements the class in which it is declared.

Up till now we have seen all the members as public members. If you wish to limit the accessibility of the members of a class, then you define class members as private or protected.


Private Member

By specifying a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.

Example

A class member can be made to become private by using private keyword infront of the member -

class MyClass {
   private $car = "skoda";
   $driver = "SRK";
   
   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   private function myPrivateFunction() {
      return("I'm  not visible outside!");
   }
}

When MyClass class is inherited by another class by making use of extends, then the myPublicFunction() will be visible, and also the $driver. The extending class won't have an access to myPrivateFunction() and $car, because they are declared private.

Protected Member

A protected property is accessible in the class which it is declared inside, and in the classes that extend that class. Protected members are not available outside of those two kinds of classes.

Example

A class member can be made protected by using the protected keyword in front of the member. Below is the different version of MyClass -

class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");
   }
}

PHP Interface

Interface

Interfaces in PHP are defined to provide a common function names to implementers. Many implementers can implement those interfaces according to their requirements.

As of Php version 5, its possible to define an interface like this -

interface Mail {
   public function sendMail();
}

Then, if another class implemented that interface, like this -

class Report implements Mail {
   // sendMail() Definition goes here
}


Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is fixed. Soon as a constant is declared, it doesn't change.

Declaring one constant is easy, as its done in this version of MyClass -

class MyClass {
   const requiredMargin = 1.7;
   
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}

In this class, requiredMargin is a constant. It is declared with the keyword const, and then under no condition can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do.

Abstract class in PHP

Abstract Classes

An abstract class is one that cannot be instantiated, instead it can be inherited. An abstract class can be declared by using the keyword anbstract, as shown below -

When you are inheriting from an abstract class, all the methods marked abstract in the parent's class declaration have to be well defined by the child; additionally, these methods must be defined with same visibility.

abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}

Note - Function definition inside an abstract must be preceded by the keyword abstract. Its not proper to have abstract function definition inside a non-abstract class.

PHP Keywords

Static Keyword

Declaring the class members or methods static makes them all accessible without requiring any instantiation of the class. A class member that is defined as static can never be accessed with an instantiated class object (though a static method can).

Example

Try the following example below -

<?php
   class Foo {
      public static $my_static = 'foo';
      
      public function staticValue() {
         return self::$my_static;
      }
   }
	
   print Foo::$my_static . "\n";
   $foo = new Foo();
   
   print $foo->staticValue() . "\n";
?>

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final, then it cannot be extended.

Example

The below example results in a Fatal error: Cannot override final method (in the code) BaseClass:: moreTesting().

<?php

   class BaseClass {
      public function test() {
         echo "BaseClass::test() called<br>";
      }
      
      final public function moreTesting() {
         echo "BaseClass::moreTesting() called<br>";
      }
   }
   
   class ChildClass extends BaseClass {
      public function moreTesting() {
         echo "ChildClass::moreTesting() called<br>";
      }
   }
?>

Calling parent constructors

Instead of writing entirely new constructor for the subclass, let us write it by simply calling the parent constructor explicitly and doing whatever is necessary in addition for instantiation of the subclass.

Example

The following below is a simple example -

class Name {
   var $_firstName;
   var $_lastName;
   
   function Name($first_name, $last_name) {
      $this->_firstName = $first_name;
      $this->_lastName = $last_name;
   }
   
   function toString() {
      return($this->_lastName .", " .$this->_firstName);
   }
}
class NameSub1 extends Name {
   var $_middleInitial;
   
   function NameSub1($first_name, $middle_initial, $last_name) {
      Name::Name($first_name, $last_name);
      $this->_middleInitial = $middle_initial;
   }
   
   function toString() {
      return(Name::toString() . " " . $this->_middleInitial);
   }
}

In the above example, we have a parent class (Name) which have two argument constructor, and a subclass (NameSub1), which has three-argument constructor. The constructor of NameSub1 works by calling it's parent's constructor explicitly using the :: syntax and setting an extra field. Likewise, the NameSub1 defines its non constructor toString() in terms of parent function that it overrides.


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to studying about PHP for C Developers.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.