PHP OOPS Interview questions and answers for freshers and experienced professionals

OOPS stands for Object Oriented Programming System.  PHP (Hypertext Pre- Processor) is a server side scripting language used in web development which is based on OOPS Language.It was originally developed by Rasmus Ledorf in 1994.

Now, if you are looking for a job which is related to PHP OOP then you need to prepare for the PHP OOP Interview Questions.

Here we have prepared the important PHP OOP Interview Questions and Answers which will help you crack the interview.



Below are important Interview Questions and Answers that are frequently asked in the interviews.

1.What is Object Oriented Programming?

Object Oriented Programming is a programming technique to design your application.It is a type of programming language principle added to php5, that helps in building complex, reusable web applications.

2.What is a Class?

A Class is blueprint or template for an object. Class contains variables and methods.

It represents all properties and behaviors of an object.

In a class, variables are called properties and functions are called methods!

3.Explain how a PHP Session works?

  1. Firstly PHP creates a 16-byte long unique identifier number (stored as a string of 32 hexadecimal characters, e.g a86b10aeb5cd56434f8691799b1d9360) for an individual session.
  2. PHPSESSID cookie passes that unique identification number to users' browser to save that number.
  3. A new file is created on the server with the same name of unique identification number with sess_ prefix (ie sess_a86b10aeb5cd56434f8691799b1d9360.)
  4. The browser sends that cookie to the server with each request.
  5. If PHP gets that unique identification number from PHPSESSID cookie (on each request), then PHP searches in the temporary directory and compares that number to the file name. If both are the same, then it retrieves the existing session, otherwise it creates a new session for that user.

4.What is the difference between GET and POST?

$_GET:

  • GET is used to request form data from specified resource.
  • GET method is the one of the common HTTP methods.
  • It can be cached
  • It can be book marked
  • This can be remains in the browser history.
  • this should never used while dealing with sensitive data.
  • We can send only lesser amount of data using GET.
  • It supports only application/x-www-form-urlencoded
  • which is less secure.
  • Data will be visible in the URL

$_POST:

  • POST method used to send data to server to create/update resource.
  • This is the most common HTTP method.
  • This can never cached.
  • It cant be bookmarked
  • We can send larger amount of data using POST method.
  • It supports application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
  • This is most secure method.
  • Data will not be visible in the URL

5. In a PHP class what are the three visibility keywords of a property or method?

To set the access rights for the class methods and variables we use access specifiers.

  1. Public: When we define class members as public, It can be accessed from anywhere, even from outside the class
  2. Private: When we define class members as private, It can be accessed from within the class itself.
  3. Protected: This is same as private, with one exception, the class members defined as protected can still be accessed from its subclass.

6.What is Encapsulation? 

  1. Which is used to hide internal implementation details of an object.
  2. visibility is the mechanism for encapsulation.
  3. we can hide using private method. it can be accessed in the same class itself.
  4. Second advantage of encapsulation is you can make the class read only or write only by providing setter or getter method.

7.What is Polymorphism?

Which is having a single form but many different implementation ways. The main purpose of polymorphism is;  Simplify maintaining applications and making them more extendable.
Basically it means PHP is able to process objects differently depending on their data type or class. This powerful feature allows you to write interchangeable objects that sharing the same interface. 

8.What is Inheritance?

When the properties and methods of the parent class are accessed by the child class the process known as inheritance.Parent class decides how and what properties to be inherited to the child class by declared visibility.

9.What is Interface and when to use an interface?

  • Interface is similar to class except that it can't contain code
  • Interface used to define methods and arguments. not the contents of method.
  • any class that uses interface it must implement all the methods defined by the interface. else it will throw fatal error.
  • Interface can be defined by using interface keyword.
  • a class can implement multiple interface.
  • It can't maintain Non-abstract methods.

        eg:
        <?php
        Interface a{
        public function a1();
        }
        Interface b{
        public function b1();
        }
        class Ab implements a,b{
        public function a1(){
        echo "a1 called";
        }
        public function b1(){
        echo "b1 called";
        }
        }
        $obj = new Ab();
        $obj->a1();
        $obj->b1();
        ?>

Interface is used when you don't know anything about implementation. (All methods are abstract)
 

10.What is Abstract class?

  1. An abstract class is used to define a skeleton or blueprint for a child class. You cannot instantiate abstract class directly as they rely on child classes to fully implement the functionality. The child classes which extends abstract class define all or some of it’s abstract method.
  2. The main purpose of abstract classes is to share common functionalities with child classes.
  3. To understand this concept let’s take an example of Animal. You don’t know the Animal until the child class extends and tell them what kind of Object(Animal) it is.


    abstract class Animal { 
      public abstract function getAnimalType();  
    }
     
    class Cow extends Animal {
       public function getAnimalType() {  
            return  "Cow";
       }     
    }
     
    class Zebra extends Animal {
       public function getAnimalType() {
          return "Zebra";
       }
    }
     
    $cow = new Cow();
    $cow->getAnimalType(); 

11.What is method overloading?

Function overloading is the ability to create multiple function of the same name with the different implementations.
Function overloading in php is used to dynamically create properties and methods. these dynamic entities are processed by magic methods. which can be used in a class for various action types.
Function overloading contains same function name and the function performs different task according to their arguements.    

Function overloading occurs when you define the same function name twice (or more) using different set of parameters. For example:

class Addition {
  function compute($first, $second) {
    return $first+$second;
  }

  function compute($first, $second, $third) {
    return $first+$second+$third;
  }
}

In the example above, the function compute is overloaded with two different parameter signatures. *This is not yet supported in PHP. An alternative is to use optional arguments:

class Addition {
  function compute($first, $second, $third = 0) {
    return $first+$second+$third;
  }
}

12.What is method overriding?

 The parent class and child class will have the same function name and same number of arguments.

An example of overriding:

<?php

class Foo {
   function myFoo() {
      return "Foo";
   }
}

class Bar extends Foo {
   function myFoo() {
      return "Bar";
   }
}

$foo = new Foo;
$bar = new Bar;
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"
?>

Function overriding occurs when you extend a class and rewrite a function which existed in the parent class:

class Substraction extends Addition {
  function compute($first, $second, $third = 0) {
    return $first-$second-$third;
  }
}

For example, compute overrides the behavior set forth in Addition.

13.What is namespaces?

  1. They allow for better organization by grouping classes that work together to perform a task
    They allow the same name to be used for more than one class
  2. A Namespace in PHP is used to encapsulate the items which are similar to that of abstraction in Object Oriented programming concepts. 
  3. Namespaces are used to establish a relationship among classes, functions, and constants. 
  4. A Namespace can be defined using the keyword The namespace keyword is reserved in PHP for its internal use to avoid conflict with the user created identifiers.

<?php 

namespace MyAPP;
function output() {
echo 'IOS!';
}
namespace MyNeWAPP;
function output(){
echo 'RSS!';
}  

?>

14.What is a final keyword in PHP and when it is used?

  1. It means if we define a method with final then it prevents us to override the method.It cant be overridden.
  2. The final keyword in PHP is used to mark either a class or a function as final. 
  3. If a class is marked as final, it cannot be extended to use its properties or methods. 
  4. It prevents its child classes from overriding a method. 
  5. If only a function is marked as final, then it can’t be extended. The final keyword was introduced in PHP 5 version. 
  6. A final declaration can be done by prefixing the class name or function name with the final keyword.

15.What is the use scope resolution operator (::)?

The scope resolution operator is used to call static methods of the class that has not been instantiated.

16.What is Constructor and Destructor?

Constructor and Destructor both are special type of functions which are automatically called when an object is created and deleted.

17.Does PHP support multiple inheritance??

PHP does not support multiple inheritance  but by using interface or TRAITS instead of classes we can implement it.        

18.How do you load PHP classes?

The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

19.What is the difference between $message and $$message in PHP?
They are both variables. But $message is a variable with a fixed name. $$message is a variable whose name is stored in $message. For example, if $message contains “var”, $$message is the same as $var. 

20. What is the difference between “echo” and “print” in PHP?
PHP echo output one or more string. It is a language construct not a function. So use of parentheses is not required. But if you want to pass more than one parameter to echo, use of parentheses is required. Whereas, PHP print output a string. It is a language construct not a function. So use of parentheses is not required with the argument list. Unlike echo, it always returns 1.
Echo can output one or more string but print can only output one string and always returns 1.
Echo is faster than print because it does not return any value.

21.What is TRAITS in php?

PHP only supports single inheritance: a child class can inherit only from one single parent.

So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Traits are declared with the trait keyword:

Eg:

<?php
trait message1 {
public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>
 
22.What is Type Hinting in PHP?
  1. Type Hinting is used to specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration.
  2. It is beneficial because it results in better code organization and improved error messages.
  3. Suppose we want to force a function to get only arguments of the type array, then we can simply put the array keyword before argument's name.
<?php
function myFunction(array $argument_name) {
//block of code
}
?>

It is also know as Type Declaration.

23.How to count objects of a class in PHP?
<?php
class countClassObjects{

    public static $count = 0;
    
    public function __construct(){
        self::$count++;
    }
    public function xyz(){
        //code
    }
}

$obj1 = new countClassObjects();
$obj2 = new countClassObjects();
$obj3 = new countClassObjects();
$obj4 = new countClassObjects();
$obj5 = new countClassObjects();

echo "The number of objects in the countClassObjects class is " . countClassObjects::$count;
?> 

There are many differences between abstract class and interface in php.

1. Abstract methods can declare with public, private and protected. But in case of Interface methods declared with public.

2. Abstract classes can have constants, members, method stubs and defined methods, but interfaces can only have constants and methods stubs.

3. Abstract classes doest not support multiple inheritance but interface support this.

4. Abstract classes can contain constructors but interface doest not support constructors.

25. How much memory does a class occupy?

Classes do not consume any memory. They are just a blueprint based on which objects are created. Now when objects are created, they actually initialize the class members and methods and therefore consume memory.

26.Is it always necessary to create objects from class?

No. An object is necessary to be created if the base class has non-static methods. But if the class has static methods, then objects don’t need to be created. You can call the class method directly in this case, using the class name

27. What are some magic methods in PHP, how might you use them?  

Magic methods are basically triggers that occur when particular events happen in your coding. __GET, __SET are magic methods that are called (behind the seen) when you get or set a class property. 

28.What does "&" mean in '&$var' ? 

'&' indicates a reference

28.Can you call the base class method without creating an instance?

Yes, you can call the base class without instantiating it if:

  • It is a static method
  • The base class is inherited by some other subclass

29.What is exception handling?

Exception handling in Object-Oriented Programming is a very important concept that is used to manage errors. An exception handler allows errors to be thrown and caught and implements a centralized mechanism to resolve them.

  1. An exception is an object that describes an error or unexpected behaviour of a PHP script.
  2. Exceptions are thrown by many PHP functions and classes.
  3. User defined functions and classes can also throw exceptions.
  4. Exceptions are a good way to stop a function when it comes across data that it cannot use.

<?php try {
  code that can throw exceptions
} catch(Exception $e) {
  code that runs when an exception is caught
}

30.In PHP, objects are they passed by value or by reference?

They are passed by value in PHP 4 and by reference in PHP 5. In order to pass objects by reference in PHP 4 you have to explicitly mark them as such:

$obj = &new MyObj;

One of the key-points of PHP OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. In PHP, an object variable doesn't contain the object itself as value. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. 

31.What is a Regular Expression?

  1. A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
  2. A regular expression can be a single character, or a more complicated pattern.
  3. Regular expressions can be used to perform all types of text search and text replace operations.

 

FunctionDescription
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
preg_replace()Returns a new string where matched patterns have been replaced with another string

 32.What is callback functions in php?

A Callback function is function which is passed as an argument into another function.

<?php
function my_callback($item) {
  return strlen($item);
}

$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
?>
 
33.What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

34.What are the superglobals in php?

PHP Global Variables - Superglobals

Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

The PHP superglobal variables are:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

 35.What is an Iterable in PHP?

An iterable is any value which can be looped through with a foreach() loop.

The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.

<?php
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

$arr = ["a", "b", "c"];
printIterable($arr);
?>
 
 
36.What is array_combine()?
Creates an array by using the elements from one "keys" array and one "values" array
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");

$c=array_combine($fname,$age);
print_r($c);
?>
 Output: Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 ) 
37.what is array_merge()?
Merges one or more arrays into one array
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )  
 
38.What is the difference between include() and require()?
Include(): when we forgot to include a file using include() it will throw warning error in php. And script will continue the execution.
require(): when we forgot to include a file using include() it will throw fatal error in php. And script will terminate the execution.
 

 

Comments