PHP OOPS Interview Questions And Answers

I Have Selected Advanced OOPS Interview Questions And Answers For Fresher/Experienced Candidates. Last Few Months I Have Been Working To Select Best Question And Answer Set For OOP Interview Questions. Object Oriented Programming In PHP. This Article Introduces Object Oriented Programming (OOP) In PHP

1. What is Object Oriented Programming ?

Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined objects.

Brief overview of object-oriented concepts and terminology:
Object.
Class.
Inheritance.
Interface.
Package.

2. Advantages of object oriented programming ?

Code Re-usability(Polymorphism,Interfaces) : In OOPs objects created in one program can be reused in different programs. Code extensibility : for adding new features or modifying existing objects can be solved by introducing new objects. Catch errors at compile time rather than at runtime. Maintainability : objects can be maintained separately, so u can easily fix errors. Imrove error handling:We can use exceptions to improve error handling. Modularity : can create seperate Modules. Modifiability : it is easy to make minor changes in some classes as Changes inside a class do not affect any other part of a program.

3. What is a Class ?

Class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of properties & behavior of an object is also called as class. A class contains properties, fields, data members, attributes.

Example:
Car is an object , cars is a class
public class cars
{
  //
}


According to the sample given below we can say that the cars object, named object_car, has created out of the cars class.
cars object_car = new cars();

4. What is the relation between Classes and Objects ?

Class is a definition, while object is a instance of the class created. class is like a blueprint/template in OOPs, and this template is used to create objects.The collection of properties & behavior of an object is also called as class. A class contains properties, fields, data members, attributes.

Example:

Car is an object , cars is a class
            public class cars
            {
                  //
            }


According to the sample given below we can say that the cars object, named object_car, has created out of the cars class.

               cars object_car = new cars();

object is an instance of a class.An object is an entity that has attributes, behavior, and identity. Objects are members of a class.
Objects are accessed, created or deleted during program run-time.

Declaration of an Object in OOPs
ClassName objectName=new ClassName();
Example:
          Car objCar= new Car();



Attribute in OOPs: Attributes define the characteristics of a class. In Class Program attribute can be a string or it can be a integer. 
Behavior in OOPS:  Every object has behavior.
Identity in OOPS:  Each time an object is created the object identity is been defined.

5. What are different properties provided by Object-oriented systems ?

1. Support inheritance. 2. Provides encapsulation of data. 3. Provides extensibility of existing data types and classes. 4. Provide support for complex data types. 5. Inheritance-one class inherite the property of another class. 6. Aggregation-.is a part whole relationship. 7. Association.:is a relationship between 1 or more instances of a class.

6. Explain about abstraction ?

Abstract Class: It may contain one or more abstract methods.abstract classes may not be instantiated.The child classes which inherits the property of abstract base class, must define all the methods declared as abstract. Any class that contains at least one abstract method must also be abstract. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

Example:

<?php
abstract class AbstractClass
{
    abstract protected function getValue();
    abstract protected function setValue($val);

    public function Display() {
        print $this->getValue() . "\n";
    }
}

class ChildClass1 extends AbstractClass
{
    protected function getValue() {
        return "ChildClass1";
    }

    public function setValue($val) {
        return "ChildClass{$val}";
    }
}

class ChildClass2 extends AbstractClass
{
    public function getValue() {
        return "ChildClass2";
    }

    public function setValue($val) {
        return "ChildClass{$val}";
    }
}

$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>

7. Explain about encapsulation ?

The wrapping of data and function together in a single unit(class) is called encapsulation. In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility, interfaces,and more.

PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods:

Public : A public variable or method can be accessed directly by any user of the class.

Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

Private: private variable or method can only be accessed internally from the class in which it is defined.

Example :
class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.
<?php 
class Shape { 
     private static $_circle; 
     public function Circle( )
    { 
          if( $this->_circle == null ) { 
               $this->_circle = new Circle(); 
          } 
          return $this->_circle; 
     } 
} 
class Circle { 

     private $_radius; 
     public function __construct() { 
          $this->_radius = "10"; 
     } 
public function GetRadius() { 
          return $this->_radius; 
     } 
}

$shape= new Shape(); 
echo $shape->Circle()->GetRadius(); 
?>

8. What is an Abstract class ?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Rules: 1.In abstract class at least one method must be abstract. 2.we can create object of abstract class. 3.Abstract classes may not be instantiated. 4.The child classes which inherits the property of abstract base class, must define all the methods declared as abstract. 5.Any class that contains at least one abstract method must also be abstract. 6.If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. 7.Abstract class can contain variables and concrete methods. 8.A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.

Example:


<?php
abstract class AbstractClass
{
    abstract protected function getValue();
    abstract protected function setValue($val);


    public function Display() {
        print $this->getValue() . "\n";
    }
}


class ChildClass1 extends AbstractClass
{
    protected function getValue() {
        return "ChildClass1";
    }


    public function setValue($val) {
        return "ChildClass{$val}";
    }
}


class ChildClass2 extends AbstractClass
{
    public function getValue() {
        return "ChildClass2";
    }


    public function setValue($val) {
        return "ChildClass{$val}";
    }
}


$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>

9. What is an Interface ?

1. In interface all the method must be abstract(only define). 2. All methods declared in an interface must be public. 3. Interfaces cannot contain variables and concrete methods except constants. 4. A class can implement many interfaces and Multiple interface inheritance is possible. 5. To extend from an Interface, keyword implements is used.

Example:

interface Shape
 {
 function getShape();
}

class Circle implements Shape{
 public function getShape() {
  return "This is Shape of the Circle\n";
 }
}

class MultiInher {
 public function read(Shape $s) {
  $shape = $s->getShape();
  //
  echo $shape;
 }
}

$c = new Circle();

$m = new MultiInher();
$m->read($c);

10. What are Abstract methods ?

An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

Example:

<?php
abstract class AbstractClass
{
    abstract protected function getValue();
    abstract protected function setValue($val);


    public function Display() {
        print $this->getValue() . "\n";
    }
}


class ChildClass1 extends AbstractClass
{
    protected function getValue() {
        return "ChildClass1";
    }


    public function setValue($val) {
        return "ChildClass{$val}";
    }
}


class ChildClass2 extends AbstractClass
{
    public function getValue() {
        return "ChildClass2";
    }


    public function setValue($val) {
        return "ChildClass{$val}";
    }
}


$class1 = new ChildClass1;
$class1->Display();
echo "<br>";
echo $class1->setValue('1') ."\n";
echo "<br>";
$class2 = new ChildClass2;
$class2->Display();
echo "<br>";
echo $class2->setValue('2') ."\n";
?>

11. What is the difference between Abstract classes and Interfaces ?

Difference :

Abstract Class :
To define a class as Abstract, the keyword abstract is to be used. 
In abstract class at least one method must be abstract.
we can create object of abstract class.
abstract classes may not be instantiated.
The child classes which inherits the property of abstract base class, must define all the methods declared as abstract.
Any class that contains at least one abstract method must also be abstract.
If the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.
Abstract class can contain variables and concrete methods.
A class can Inherit only one Abstract class and Multiple inheritance is not possible for Abstract class.

Interfaces :
In interface all the method must be abstract.
All methods declared in an interface must be public.
Interfaces cannot contain variables and concrete methods except constants.
A class can implement many interfaces and Multiple interface inheritance is possible.
To extend from an Interface, keyword implements is used.

12. What is difference between Static and Non-Static fields of a class ?

In this Article,I will explain how to use Static Keyword in PHP5. To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword. Static properties or methods can be accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object. $this is not available inside the method declared as static. Static properties cannot be accessed using the arrow operator ->. Static properties can be accessed using the Scope Resolution Operator (::) operator. ClassName::$staticvar= $value;

Example:


<?php
class Box
{
   static private $color;  

   function __construct($value)
   {
  if($value != "")
  {
   Box::$color = $value; 
  }
  $this->getColor();
   }

   public function  getColor ()
   {
  echo Box::$color;
   }
}

$a = new Box("RED");
$a = new Box("GREEN");
$a = new Box("");
?>

OUTPUT:
RED
GREEN
GREEN

13. Static Methods and Properties ?

Static Methods and Properties: In this Article,I will explain how to use Static properties or methods in PHP5. To implement static keyword functionality to the attributes or the methods will have to be prefix with static keyword. Static properties or methods can be accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object. $this is not available inside the method declared as static. Static properties cannot be accessed using the arrow operator ->. Static properties can be accessed using the Scope Resolution Operator (::) operator. ClassName::$staticvar= $value;

Example:

<?php 
class Box
{
   static private $color;  
   function __construct($value)
   {
  if($value != "")
  {
   Box::$color = $value; 
  }
  $this->getColor();
   }
   public function getColor()
   {
  echo Box::$color ;
   }
    
   static public function StaticMethod() {


        echo self::$color;


    }


}
$a = new Box("RED");
Box::StaticMethod();
$a = new Box("GREEN");
$a = new Box("");
?>


OUTPUT:
RED
RED 
GREEN
GREEN

14. What is a constructor and Destructor in class ?

PHP 5 allows developers to declare constructor methods for classes.Classes call constructor method on each newly-created object.

function __construct() {
//
}
Example:


<?php
class MainClass {
   function __construct() {
      echo "In MainClass constructor\n";
   }
}


class ChildClass extends MainClass {
   function __construct() {
       parent::__construct();
      echo "In SubClass constructor\n";
   }
}


$obj = new MainClass();
$obj = new SubClass();
?>
Note: If  PHP 5 cannot find a __construct() function for a given class, it will search for the old constructor function, by the name of the class.  


Destructor:


The destructor method will be called as soon as Classes destroy the object.


 function __destruct() {
  //     
   }
Example:


<?php
class MainClass {
   function __construct() {
      echo "In MainClass constructor\n";
   }
function __destruct() {
       print "Destroying \n";
   }
}
class ChildClass extends MainClass {
   function __construct() {
       parent::__construct();
      echo "In SubClass constructor\n";
   }
   
}


$obj = new MainClass();
$obj = new SubClass();
?>


Note: The destructor method will be called even if script execution is stopped using exit().

15. What are access modifiers ?

Access modifier: OOP provides data-hiding capabilities with public, protected, and private data attributes and methods: Public : A public variable or method can be accessed directly by any user of the class. Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class. Private : A private variable or method can only be accessed internally from the class in which it is defined.

16. What is serialization ?

Serialization/UnSerialization : 1. Generates a storable representation of a value. 2. serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. 3. unserialize() can use this string to recreate the original variable values. 4. This process makes a storable representation of a value that is useful for storing or passing PHP values. 5. To make the serialized string into a PHP value again, use unserialize(). <br> Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method. Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method. What can you Serialize and Unserialize? Variables Arrays Objects What cannot you Serialize and Unserialize? Resource-type

Example:
//BaseClass.php
<?php

  class BaseClass {
      public $var = 100;
    
      public function show() {
          echo $this->var;
      }
  }
  
// test1.php:


  include("BaseClass.php");
  
  $a = new A;
  $v = serialize($a);
  file_put_contents('store_in_var', $v);


// page2.php:
  
  include("BaseClass.php");
  $v = file_get_contents('store_in_var');
  $a = unserialize($v);




  $a->show();
?>

In the Case if you want to store entire array into database then with serialze() it would be useful to store an entire array in a field in a database.
You can pass an array to the function, and it will return a string that is essentially the string. 
You can then unserialize() it to obtain the full array once again.


example:


<?php

$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);
echo $serialized_str;


?>


This will output a:3:{i:0;s:14:"Rajesh Sharma";i:1;s:6:"Rajesh";i:2;s:7:"RajeshS";}
so you can store entire array in a field in a database.


<?php

$str_array = array( "Rajesh Sharma", "Rajesh", "RajeshS" );
$serialized_str = serialize($str_array);


print_r(unserialize($serialized_str));


?>
This will output a Array ( [0] => Rajesh Sharma[1] => Rajesh [2] => RajeshS ).

17. Explain about inheritance in OOPS ?

In this tutorial we will study about Inheritance. Inheritance is a mechanism of extending an existing class. In Inheritance child class inherits all the functionality of Parent Class. For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods.

<?php


class BaseClass
{
    public function GetValue($string)
    {
        echo 'BaseClass:'. $string ;
    }


    public function setValue($string)
    {
        echo  $string;
    }


    
}


class ChildClass extends BaseClass
{
    public function GetValue($string)
    {
        echo 'ChildClass:'. $string ;
    }
}


$b = new BaseClass();
$c = new ChildClass();


$b->GetValue('Rajesh Test'); // Output: 'BaseClass: Rajesh Test'
$b->setValue('Rajesh Test'); // Output: 'Rajesh Test'
$c->GetValue('Rajesh Tutorials'); // Output:'ChildClass: Rajesh Tutorials'
$c->setValue('Rajesh Test'); // Output: 'Rajesh Test'


?>

18. What is Encapsulation?

The wrapping of data and function together in a single unit(class) is called encapsulation. In PHP 4 objects were little more than arrays.In PHP 5 you get much more control by visibility, interfaces,and more. PHP5 provides data-hiding capabilities with public, protected, and private data attributes and methods: Public : A public variable or method can be accessed directly by any user of the class. Protected : A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class. Private: private variable or method can only be accessed internally from the class in which it is defined. E.g.: class is a protective wrapper which binds data and methods together,they can be accessed only though object of that class.

Example:


<?php 


class Shape { 


     private static $_circle; 


     public function Circle( ) { 
          if( $this->_circle == null ) { 
               $this->_circle = new Circle(); 
          } 
          return $this->_circle; 
     } 


} 


class Circle { 


     private $_radius; 


     public function __construct() { 
          $this->_radius = "10"; 
     } 


     public function GetRadius() { 
          return $this->_radius; 
     } 
} 


$shape= new Shape(); 


echo $shape->Circle()->GetRadius(); 
?>

19. Explain about polymorphism ?

In this tutorial we will study about polymorphism. Polymorphism in PHP5 : To allow a class member to perform diffrent tasks. polymorphism where the function to be called is detected based on the class object calling it at runtime.

Example:
< ?
class Person
{
    public function Talk()
    {
         echo "English";
    }
}

class Language extends Person
{
      public function Talk()
      {
           echo "French";
      }


}

function CallMethod(Person $p)
{
      $p->Talk();
}



$l = new Language();
CallMethod($l);
?>


Output:
French;

Social Share

Leave a Reply