April 7, 2014 3:16 pm

Object Oriented Programming (OOP) for beginner in PHP

PHP start OOP in PHP 4 and a stable model of Object Oriented Programming (OOP) introduced in PHP 5 in 2004. We all making applications in procedural programming and want to move to OOP way, Object Oriented is an style of coding that allows programmers to group similar tasks into classes, using Object Oriented Programming you can easily maintain your code. Before going to explain OOP let me give you some real example like universe made of different objects like sun, mars, moon etc, a car made of different objects like steering, engine, break etc.

object-oriented-programming-oop-for-beginner-in-php

Object Oriented Concepts:

Lets define important terms related to Object Oriented Programming.

Class: Class is a term used in the OOP paradigm. They provide abstraction, modularity and much more to your code.

Member function: Functions created inside a class are known as member function.

Member Variable: Variables defined inside the class called member variable. These variables also called attribute of the object.

Object: Object is instance defined by your class. Define one class and create many objects of that class.  Objects are also known as instance.

Inheritance: Inheritance is most useful tools of OOP. Inheritance allows you to create one or more classes derived from a base class ( also called parent class ).

Parent class: Class inherited by another class. This is also called a base class or super class.

Child Class: A class that inherits from another class. This is also called a subclass or derived class.

Polymorphism: Poly (meaning many) and morph (meaning forms). Different behaviors for the same operation.

Overloading: Overloading means to replacing the same parental behavior in child class.

Data Abstraction: Representation of data in which the implementation details are hidden (abstracted).

Encapsulation: One of the biggest advantage of OOP is Encapsulation or data hiding. It hides the data from being accessed from outside a class directly.

Constructor: Classes with a constructor method call this method on each object creation, initialization that the object may need before it is used.

Destructors: Function which will be called automatically whenever an object is deleted or goes out of scope.

Structuring Classes

Creating a class is very simple and easy declaring a class using class keyword followed by the name of that class.

<?php
    class myFirstClass {
        #code
    }
?>

This is how you can create a class and insert your code inside it.

Member function

<?php
    class myFirstClass {

        function myFunction(){
            echo "function 1";
        }

    }
?>

Member Variable:

<?php
    class myFirstClass {
        $var1 = "hello";
        $var2;
    }
?>

Creating Objects in PHP

Once you created you class now create that class object as many as you want.

<?php
$objc1 = new myFirstClass();
$objc2 = new myFirstClass();
?>

This is how we create an object of a class.

Calling member function of a class

<?php
  $obj = new myFirstClass(); // object of the class

  $obj->myFunction(); // member function call
?>

Inheritance

PHP class can be inherited from a parent class by using extends keyword syntax as below.

<?php
    class myFirstClass {

        function myFunction(){
            echo "function 1";
        }

    }
    class childClass extends myFirstClass  {
        #code
    }
?>

The child class (or subclass or derived class) has these characteristics

1. Member variable declaration.

2. Same member functions as the parent and all work same as parent work.

Here childClass is the the Child Class of Parent Class myFirstClass.

Polymorphism

Polymorphism means different behavior for same operation like animal talk behavior is same talk but sound is different from all animals.

class animalClass {
      protected $name;
      public function __construct($animalName)
      {
         $this->name = $animalName;
      }

      public function getName()
      {
         return $this->name;
      }

      public function talk()
      {
         return $this->getName().' is talking <br />';
      }
   }

   class dogClass extends animalClass
   {
      public function getName()
      {
         return 'Dog: '.parent::getName();
      }
   }

$a = new dogClass("My dog");
echo $a->talk();
$b = new animalClass("some Cat");
echo $b->talk();

Different animals different voice but same method talk.

Overloading

Method overloading is where a class has two or more functions of the same name, but accepting a different number and/or data types of parameters.

In PHP, overloading means you can add object members at run-time, by implementing some of the magic methods like __set, __get, __call etc.

class myClass {
    public function __call($method, $args) {

        if ($method === 'myFunction') {
            echo 'Sum is calculated to ' . $this->getSum($args);
        } else {
            echo "Called method $method";
        }
    }

    private function getSum($args) {
        $sum = 0;
        foreach ($args as $arg) {
            $sum += $arg;
        }
        return $sum;
    }
}

$obj = new myClass;
$obj->myFunction(10,25,30,12);
$obj->myFunction(21,20,1);

Encapsulation

Encapsulation hides data being accessed from outside a class directly.

There is 3 types in encapsulation:

Public Members:

Its a default state of methods and properties of a class, can be accessed outside the class, within the class and in an other class that implements the class.

If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private Members:

By describing a member private you limit it to be accessed to the class in which it is declared. A class member can be made private by using private keyword in front of the member.

<?php
    class myFirstClass {
        function myFunction(){
            echo "public one";
        }
        private function myPrivateFunction(){
            echo "I'm  not visible outside!";
        }
    }
?>

If any class extends this class not able to access myPrivateFunction just because of its a private property of this class.

Protected Members:

A class with protected property or method can be accessible within the class and it can be accessed in the class which extends that class. A class member can be made protected by using protected keyword infront of the member.

<?php
    class myFirstClass {
        function myFunction(){
            echo "public one";
        }
        protected function myprotectedFunction(){
            echo "I'm  visible in child class!";
        }
    }
?>

Constructor Functions:

Constructor function is a function which called when object created of the class. So we can use this to take its advantage and initialize many things on object creation.

<?php
    class myFirstClass {
        __construct($par1, $par2){
            $this->price = $par1;
            $this->title = $par2;
        }
        function myFunction(){
            echo $this->price." ".$this->title;
        }
    }
    $obj = new myFirstClass('Hello',7);
    $obj->myFunction();
?>

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

Destructor:

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor.

So that’s all for today’s tutorial and I hope it helps the and please don’t forget to give me your feedback.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

6 responses to “Object Oriented Programming (OOP) for beginner in PHP”

  1. excellent! i love oops concept generally!

  2. vydyas says:

    Hiee everything is okk but please change the header of page or mnimize the logo size

  3. saltun says:

    :'( Do not close your PHP tags

  4. Thirumani Raj says:

    awesome! I like oops concept. Its easy to uderstand. Really good work. Will you please give some dynamic website example using oops php and mysql. Fetching the content from Database..

  5. Theodis Butler says:

    I need help! I created an RSS feeed using SimpleXML and procedural style programming based upon a tutorial on this site. It generates a sitemap when loaded.

    One day I decided to use a PHP class written in OOP style that has the ability to parse RSS feeds. No matter what I do, when I use this class, it outputs my sitemap from an entirely different php script! How is this possible? How can I fix this?

  6. Ye Htun says:

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *