Sunday, October 11, 2020

Object Oriented Programming in PHP



Hello dear readers! welcome back to another section of my tutorial on PHP. In this tutorial guide, we will be discussing about OOPS in PHP.

We can imagine our apartments made of various objects like TV sets, tables, gas cookers and so on. In same way there is an object oriented programming notion  that assume everything as an object and executes 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 & 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.

RECOMMENDED: PHP and XML Tutorial


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.

RECOMMENDED POST: How to use AJAX in PHP


Creating Objects in PHP

Once your class is defined, then 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 not in any way dependent on each other and they exist separately. Let us now see how to access the member function and also process member variables.

Calling Member Functions

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

Example

Following example shows how to set the 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 can then call another member functions 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 Functions

Constructor are special types of functions which are automatically called when an object is produced. So we take complete advantage of this behaviour, by utilizing so many things making use of constructor functions.

PHP provides a special function called _construct() for defining a constructor. You can pass as many arguments as you like into the constructor function.

Example

The following example will create a constructor for Books class and it will initialize 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 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

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.

RECOMMENDED: PHP Date and Time

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 then adds more functionality to it based upon 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, class Novel keeps two extra member functions.


Function Overriding

The function definitions in child classes overrides definition which have the same name in parent classes. In a child class, we can modify the definition of function inherited from parent class.

Example

Following example 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

Except you specify otherwise, the 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 its declared. The private member can't be referred to from classes that inherit the class in which it is declared and can't 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 making use of extends, then myPublicFunction() will be visible, and also the $driver. The extending class won't have an access to the myPrivateFunction() and $car, because they're declared private.

Protected Member

A protected property or method is accessible in the class which it is declared inside, and also in the classes that extend that class. The protected members aren't 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!");
   }
}


Interface

Interfaces in PHP are defined to provide a usual 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 executed that interface, like this -

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

RECOMMENDED: PHP MySQL Database

Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a function a constant is fixed. As soon as a constant is declared, it does not 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 above 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 Classes

Anbstract class is one that can not 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.


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 to it users the final keyword, that prevent child classes from overriding a method by simply 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 an entirely new constructor for the subclass, let us write it by just 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 also defines its non constructor toString() in terms of parent function that it overrides.

RECOMMENDED: PHP Decision Making

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

Feel free to ask your questions where necessary and i 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.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.