Most asked Object Oriented Interview Questions in PHP – Part -1

In this article we are going to discuss about some important concepts of Object oriented PHP in a questions answer form.

In this article we are going to look at some of the most asked Object Oriented Interview Questions in PHP.

1. What are Object Oriented Concepts that can be implemented with PHP?

PHP supports a wide range of object-oriented concepts that can be implemented to create structured, modular, and maintainable code. Here are some key object-oriented concepts that can be implemented with PHP:

The core object oriented features of PHP are

  1. Classes and Objects: PHP allows you to define classes and create objects based on those classes. Classes serve as blueprints for objects, encapsulating properties (attributes) and methods (functions) that operate on those properties.
  2. Encapsulation: PHP supports encapsulation by using access modifiers (public, protected, private) to control the visibility of properties and methods. This helps in maintaining data integrity and controlling access to object internals.
  3. Inheritance: Inheritance allows you to create a new class (subclass) based on an existing class (superclass). PHP supports single inheritance, multilevel inheritance and Hierarchical inheritance enabling you to reuse code and extend functionality.
  4. Polymorphism: Polymorphism in PHP allows objects of different classes to be treated as objects of a common superclass. It’s achieved through interfaces, abstract classes, and method overriding.
  5. Abstraction: Abstraction involves defining the essential features of an object while hiding unnecessary details. Abstract classes and interfaces in PHP enable you to create abstract concepts that can be implemented by concrete classes.

Let’s take a look some other object orientated implementations in PHP

  1. Interfaces: PHP supports interfaces, which define a contract that classes must adhere to by implementing the specified methods. This allows for standardized behavior across different classes.
  2. Abstract Classes: Abstract classes cannot be instantiated directly and are meant to be subclassed. They provide a way to create a common base for related classes, allowing you to define common methods and properties.
  3. Method Overriding: PHP allows you to override methods from parent classes in child classes, enabling you to customize behavior while maintaining a common interface.
  4. Method Overloading: While PHP does not support traditional method overloading (methods with the same name but different parameter lists), you can achieve similar effects by using default parameter values or using variadic functions.
  5. Final Classes and Methods: You can mark classes as final to prevent them from being subclassed. Similarly, you can mark methods as final to prevent them from being overridden in subclasses.
  6. Static Methods and Properties: PHP supports static methods and properties that belong to the class itself rather than to instances of the class. Static members are accessed using the :: operator.
  7. Constructor and Destructor: PHP classes can have constructor (__construct) and destructor (__destruct) methods. Constructors are called when objects are created, while destructors are called when objects are no longer referenced.
  8. Autoloading: PHP provides autoloading mechanisms that automatically load class files when they’re needed, simplifying the process of including class files.
  9. Traits: Traits allow for code reuse across classes in different inheritance hierarchies. They are used to include methods and properties in classes without using inheritance.
  10. Namespaces: Namespaces in PHP help organize classes into logical groups, preventing naming conflicts and improving code organization.

2. Explain Encapsulation with example in PHP ?

Encapsulation is the process of combining data and functions into a single unit. This makes it easier to manage the data and functions, and it also helps to protect the data from unauthorized access. In PHP, encapsulation can be implemented using access modifiers.

Let’s check encapsulation with an example

<?php 
class BankAccount {
    private $balance;

    public function setBalance($amount) {
        if ($amount >= 0) {
            $this->balance = $amount;
        }
    }

    public function getBalance() {
        return $this->balance;
    }
}

$account = new BankAccount();
$account->setBalance(1000);
echo $account->getBalance(); // 1000
?>

In this example $balance property of BankAccount class has been declared as private. So it can’t be accessed from outside the class. In order to access the $balance property we have used two methods one for setting the value of the property setBalance() and another for getting the value of the property getBalance(). Both the methods have been declared as public. So both the methods can be accessed from outside the class as well as they have access to the $balance. These methods doesn’t tell you how the value is getting stored or retrieved in turn ensures any unauthorized access to the private property $balance. So here in this example the methods and properties (functions and data) are encapsulated within the class BankAccount.

3. What is inheritance and how it is used in PHP?

Inheritance is a concept in object-oriented programming that allows one class (child class/ subclass/ derived class/) to inherit the properties and methods of another class(parent class/superclass/base class) and it can also add its own properties and methods or override the ones inherited from the superclass. In PHP . PHP supports 3 types of inheritance Single Inheritance, Multilevel Inheritance and Hierarchical Inheritance.

Single Inheritance: In this type of inheritance only one class be inherited by a single class.

Let’s understand with an example

<?php 
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

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

    public function getAge() {
        return $this->age;
    }

    public function setAge($age) {
        $this->age = $age;
    }
}

class Male extends Person{
    private $gender;
    public function __construct($name, $age,$gender) {
      parent::__construct($name,$age);
      $this->gender = $gender;
    }
    public function setValues($name,$age, $gender){
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }

    public function getValue(){
        return 'Name-'.$this->name.'Age- '.$this->age.' Gender-'.$this->gender; 
    }

}

$male = new Male('Jon', 24,'Male'); 
echo $male->getValue(); //Name-Jon Age- 24 Gender-Male
?>

Here class Male got inherited from class Person . Here Person is the superclass of class Male

Multilevel Inheritance: It is a type of inheritance in which a class inherits from another class, which in turn inherits from another class. This allows for the creation of complex class hierarchies that can be used to model real-world relationships.

Multiple Inheritance

Lets understand it with an example

<?php 
class Animal {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function speak() {
        return "I am an animal!";
    }
}

class Dog extends Animal {
    public function bark() {
        return "Woof!";
    }
}

class GoldenRetriever extends Dog {
    public function fetch() {
        return "I can fetch!";
    }
}

$dog = new GoldenRetriever("Spot", 10);
echo $dog->speak(); // I am an animal!
echo $dog->bark(); // Woof!
echo $dog->fetch(); // I can fetch!
?>

In this example, the GoldenRetriever class inherits from the Dog class, which in turn inherits from the Animal class. This means that the GoldenRetriever class has all of the properties and methods of the Animal and Dog classes.

When we create a new GoldenRetriever object, we pass the name “Spot” and the age 10 to the constructor. The constructor then sets the name and age properties of the GoldenRetriever object to the values that we passed in.

We can then call the speak(), bark(), and fetch() methods on the GoldenRetriever object. The speak() method will return the string “I am an animal!”, the bark() method will return the string “Woof!”, and the fetch() method will return the string “I can fetch!”.

Hierarchical Inheritance: Hierarchical inheritance is a type of inheritance in which a single class is inherited by multiple classes. This allows for the creation of a tree-like hierarchy of classes, where each class inherits from the class above it.

Hierarchical Inheritance

Let’s understand this with an example

<?php 
class Animal {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function speak() {
        return "I am an animal!";
    }
}

class Dog extends Animal {
    public function bark() {
        return "Woof!";
    }
}

class Cat extends Animal {
    public function meow() {
        return "Meow!";
    }
}

$dog = new Dog("Spot", 10);
echo $dog->speak(); // I am an animal!
echo $dog->bark(); // Woof!

$cat = new Cat("Simba", 5);
echo $cat->speak(); // I am an animal!
echo $cat->meow(); // Meow!
?>

In this example, the Dog and Cat classes both extend from the Animal class. This means that they both have all of the properties and methods of the Animal class.

The Dog class also has its own bark() method, and the Cat class also has its own meow() method.

When we create a new Dog object, we pass the name “Spot” and the age 10 to the constructor. The constructor then sets the name and age properties of the Dog object to the values that we passed in.

We can then call the speak(), bark() methods on the Dog object. The speak() method will return the string “I am an animal!”, and the bark() method will return the string “Woof!”.

When we create a new Cat object, we pass the name “Simba” and the age 5 to the constructor. The constructor then sets the name and age properties of the Cat object to the values that we passed in.

We can then call the speak(), meow() methods on the Cat object. The speak() method will return the string “I am an animal!”, and the meow() method will return the string “Meow!”.

Advantages of Inheritance :

  • Code reuse: Hierarchical inheritance allows us to reuse the code from a single class in multiple classes. This can save us time and effort when developing software.
  • Abstraction: Hierarchical inheritance can be used to abstract away the implementation details of a single class. This makes the code easier to understand and maintain.
  • Extensibility: Hierarchical inheritance allows us to extend the functionality of a single class without modifying the original class. This makes the code more flexible and adaptable to change.
  • Refactoring: Hierarchical inheritance can be used to refactor code in a way that makes it easier to understand and maintain. This can improve the quality of the code and make it easier to update in the future.

4. What is interface and how interface has been implemented in PHP ?

An interface in PHP is a programming construct that defines a contract of methods that classes must implement. It allows you to specify a set of method signatures that any class implementing the interface must provide. Interfaces are used to define a common set of behaviors that different classes can adhere to, promoting code standardization, modularity, and polymorphism.

Here’s how you define and implement an interface in PHP:

Defining an Interface:

interface Printable {
    public function printContent();
}

In this example, the Printable interface defines a single method printContent() that any class implementing the interface must have.

Implementing an Interface:

class Document implements Printable {
    private $content;

    public function __construct($content) {
        $this->content = $content;
    }

    public function printContent() {
        echo $this->content;
    }
}

In this example, the Document class implements the Printable interface by providing the required printContent() method.

Using the Interface:

function printDocument(Printable $document) {
    $document->printContent();
}

$doc = new Document("Hello, world!");
printDocument($doc);  // Hello, world!

Here, the printDocument() function accepts any object that implements the Printable interface. This function demonstrates polymorphism – it can work with different classes as long as they adhere to the contract defined by the interface.

Key points about interfaces in PHP:

  • A class can implement multiple interfaces, but it can only inherit from one class.
  • Interfaces do not contain any implementation; they only declare method signatures.
  • Classes implementing an interface must provide concrete implementations for all methods declared in the interface.
  • Interfaces are useful for enforcing a consistent API across different classes.

5. What is Abstract class ? Explain with some examples?

An abstract class in PHP is a class that cannot be instantiated on its own but serves as a blueprint for other classes. It can contain both abstract methods (methods without implementations) and concrete methods (methods with implementations). Abstract classes provide a way to define common functionality that subclasses can inherit while also enforcing certain method contracts.

Defining an Abstract Class:

abstract class Shape {
    abstract public function calculateArea();
}

In this example, the Shape abstract class defines an abstract method calculateArea(). Any class that extends Shape must implement this method.

Extending an Abstract Class:

class Circle extends Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

In this example, the Circle class extends the Shape abstract class and provides an implementation for the abstract method calculateArea().

Using Abstract Classes:

$circle = new Circle(5);
echo "Circle Area: " . $circle->calculateArea();  // Circle Area: 78.539816339745

Abstract classes allow you to define common behavior that multiple subclasses can share, while also enforcing a consistent structure. Abstract methods ensure that subclasses provide their own implementation for critical methods.

Key points about abstract classes in PHP:

  • Abstract classes cannot be instantiated directly; they serve as a foundation for subclasses.
  • Abstract classes can contain both abstract methods and concrete methods with implementations.
  • Subclasses that extend an abstract class must implement all abstract methods declared in the abstract class.
  • Abstract classes are often used to create base classes that encapsulate shared logic or provide a consistent API for subclasses.

6. What is method overriding in PHP ? Explain with example

Method overriding in PHP allows a subclass to provide a specific implementation for a method that is already defined in its parent class. The overridden method in the subclass has the same name and parameters as the method in the parent class. This concept allows you to customize behavior and provide specialized implementations in subclasses.

Let’s understand with an example

<?php 
class Animal {
    public function speak() {
        return "Animal sound";
    }
}

class Dog extends Animal {
    public function speak() {
        return "Woof!";
    }
}

class Cat extends Animal {
    public function speak() {
        return "Meow!";
    }
}

$animal = new Animal();
echo $animal->speak();  // Animal sound

$dog = new Dog();
echo $dog->speak();     //  Woof!

$cat = new Cat();
echo $cat->speak();     // Meow!
?>

In this example:

  • The Animal class defines a method speak() with a default implementation returning “Animal sound”.
  • Both the Dog and Cat classes extend Animal and override the speak() method with their own implementations.

When you call the speak() method on an object of the respective class, the overridden method in the subclass is invoked, providing the specialized behavior.

Key points about method overriding in PHP:

  • The method in the subclass must have the same name, parameters, and visibility as the method in the parent class.
  • The parent:: keyword is used to explicitly call the overridden method from the parent class within the subclass.
  • Overriding methods allows you to create specialized behavior in subclasses while still adhering to the common method signature defined in the parent class.
  • Method overriding is a way to achieve polymorphism, where different objects of the same class hierarchy can be treated interchangeably.

7. What is method overloading in PHP ? Explain with example

Unlike some other programming languages, PHP does not support traditional method overloading, where you can define multiple methods with the same name but different parameters. In PHP, you can’t have multiple methods with the same name in a class that only differ by the number or types of parameters.

However, you can achieve similar functionality using default parameter values or variable-length argument lists. Let’s see how this works:

Let’s understand with an example

Using Default Parameter Values:

class Calculator {
    public function add($a, $b = 0) {
        return $a + $b;
    }
}

$calc = new Calculator();
echo $calc->add(5);      // Output: 5
echo $calc->add(5, 3);   // Output: 8

In this example, the add() method in the Calculator class has a default value of 0 for the second parameter. If you call add(5), the second parameter defaults to 0.

Using Variable-Length Argument Lists (Variadic Functions):

class Calculator {
    public function add(...$numbers) {
        return array_sum($numbers);
    }
}

$calc = new Calculator();
echo $calc->add(5);          // Output: 5
echo $calc->add(5, 3, 2);    // Output: 10

Here, the add() method uses the ...$numbers syntax to accept a variable number of arguments. The array_sum() function is used to add up all the arguments.

While PHP doesn’t support traditional method overloading, these approaches allow you to create flexible methods that can handle different numbers of arguments or provide default values when arguments are missing.

8. What is static method in PHP ? Explain with an example

A static method in PHP is a method that belongs to the class itself, rather than to instances of the class. This means you can call a static method using the class name, without needing to create an object of that class. Static methods are often used for utility functions or methods that don’t depend on instance-specific data.

Defining a Static Method:

class MathUtility {
    public static function add($a, $b) {
        return $a + $b;
    }
}

In this example, the add() method is declared as static using the static keyword.

Calling a Static Method:

$result = MathUtility::add(5, 3);
echo $result;  // 8

You can call the static method directly using the class name, followed by ::.

Using a Static Method Inside the Class:

class MathUtility {
    public static function add($a, $b) {
        return $a + $b;
    }

    public static function addThree($num) {
        return self::add($num, 3);  // Using another static method inside a static method
    }
}

$result1 = MathUtility::add(5, 3);
$result2 = MathUtility::addThree(7);
echo $result1;  // Output: 8
echo $result2;  // Output: 10

In this example, the static method addThree() calls the static method add() within the same class.

Key points about static methods in PHP:

  • Static methods can’t access instance-specific properties or methods since they don’t have access to $this.
  • You can’t use the self:: keyword to call a static method from an instance method. Instead, use static::.
  • Static methods are often used for utility methods, factory methods, and methods that perform tasks not dependent on object state.
  • Static methods are called using the class name, and they don’t require an object to be instantiated.

9. What is static property ? Explain with example

A static property in PHP is a property that belongs to the class itself, rather than to instances of the class. This means you can call a static property using the class name, without needing to create an object of that class. Static properties are declared using static keyword

Defining a Static Property :

class MathUtility {
    public static $PI = 3.14159
}

Calling a Static Property:

echo MathUtility::$PI //  3.14159

Using Static Properties inside the class

class MathUtility {
    public static $PI = 3.14159;
    private $radius;
    public function __construct($radius){
       $this->radius = $radius;
    }
    
    public function areaofacircle(){
        return self::$PI*$this->radius*$this->radius;
    }
}

const mathutil = new MathUtility(10);
echo 'Area of the circle is - '. mathutil->areaofacircle(); //Area of the circle is -314.159 

Calling a Static Property from Child Class

class MathUtility {
    public static $PI = 3.14159;
    
}

class CircleUtility extends MathUtility{
  public $radius = 3.14159;
  public function __construct($radius){
       $this->radius = $radius;
    }
    
    public function areaofacircle(){
        return parent::$PI*$this->radius*$this->radius;
    }
} 

const circle = new CircleUtility(10);
echo 'Area of the circle is - '. circle->areaofacircle(); //Area of the circle is -314.159 

Instead of self:: use parent:: to access the static property of the parent class

10. What is constructor and destructor ? Explain with example

A constructor and a destructor are special methods that can be defined in a class to perform specific tasks when an object is being instantiated (created) or destroyed. The constructor is called automatically when an object is created, while the destructor is called automatically when an object is no longer referenced or explicitly destroyed.

Constructor:

The constructor method in PHP is named __construct(). It’s automatically called when an object is created from a class. You can use the constructor to initialize properties or perform any setup tasks required for the object.

Here’s an example

class Person {
    private $name;

    public function __construct($name) {
        $this->name = $name;
        echo "A new person named $name has been created." . PHP_EOL;
    }

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

$person = new Person("Alice");  // Output: A new person named Alice has been created.
echo $person->getName();        // Output: Alice

In this example, the __construct() method sets the name property of the Person object when it’s created.

Destructor:

The destructor method in PHP is named __destruct(). It’s called automatically when an object is no longer referenced or explicitly destroyed using the unset() function.

Here’s an example:

class Resource {
    public function __destruct() {
        echo "Resource is being released." . PHP_EOL;
    }
}

$resource1 = new Resource();  // No output yet
$resource2 = new Resource();  // No output yet

unset($resource1);  // Output: Resource is being released.

In this example, the __destruct() method is called when the unset($resource1) statement is executed, releasing the resources associated with the $resource1 object.

Some points to be noted about constructors and destructors in PHP:

  • A class can have only one constructor, and its name is fixed as __construct().
  • A class can have only one destructor, and its name is fixed as __destruct().
  • Constructors are called automatically when objects are created, and destructors are called automatically when objects are destroyed.
  • Constructors are often used to initialize object properties and perform setup tasks, while destructors are used to perform cleanup tasks like releasing resources.

Previous post Angular Routing and Navigation: Building Single-Page Applications
Next post Most asked Object Oriented Interview Questions in PHP – Part -2