PHP OOP


PHP OOP Interview with follow-up questions

1. What is Object-Oriented Programming (OOP) in PHP?

Object-Oriented Programming (OOP) in PHP is a programming paradigm that models software as a collection of objects — self-contained units that bundle state (properties) and behavior (methods). PHP has had OOP support since PHP 3, with substantial improvements in PHP 5, 7, and 8.

Core OOP building blocks in PHP:

class Animal {
    public function __construct(
        protected string $name,
        protected int $age,
    ) {}

    public function speak(): string {
        return 'Generic sound';
    }
}

class Dog extends Animal {
    public function speak(): string {
        return 'Woof!';
    }
}

$dog = new Dog('Rex', 3);
echo $dog->speak(); // "Woof!"

Why OOP matters in PHP:

  • Organization: Groups related data and behavior, reducing global state and function sprawl.
  • Reuse: Inheritance and interfaces allow sharing and extending behavior.
  • Frameworks: Laravel, Symfony, and every modern PHP framework are built entirely with OOP. Understanding classes, interfaces, traits, and dependency injection is essential for framework usage.
  • Testability: Objects with injected dependencies are easy to mock and unit test.

Modern PHP OOP features (8.x):

  • Constructor property promotion
  • Readonly properties and classes
  • Enums
  • Intersection types
  • First-class callables
  • Named arguments on constructors
↑ Back to top

Follow-up 1

Can you explain the concept of 'class' and 'object' in OOP?

In OOP, a class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that an object of that class will have. An object, on the other hand, is an instance of a class. It represents a specific entity or concept and can have its own unique values for the class's properties.

Follow-up 2

What are the benefits of using OOP in PHP?

Using OOP in PHP has several benefits:

  1. Code reusability: OOP allows you to create reusable classes and objects, reducing code duplication and making your code more maintainable.

  2. Modularity: OOP encourages modular code by organizing related properties and methods into classes, making it easier to understand and modify.

  3. Encapsulation: OOP provides encapsulation, which means that the internal details of an object are hidden from the outside world. This improves code security and reduces the risk of unintended modifications.

  4. Inheritance: OOP supports inheritance, allowing you to create new classes based on existing ones. This promotes code reuse and allows for the creation of more specialized classes.

  5. Polymorphism: OOP supports polymorphism, which means that objects of different classes can be treated as objects of a common superclass. This allows for more flexible and extensible code.

Follow-up 3

How does OOP improve code reusability?

OOP improves code reusability in PHP through the use of classes and objects. By creating classes that define the properties and behaviors of objects, you can create reusable code that can be used in multiple parts of your application.

For example, let's say you have a class called 'User' that represents a user in your application. This class can have properties like 'name', 'email', and 'password', as well as methods like 'register' and 'login'. By creating objects of this class, you can easily create and manage users throughout your application.

Furthermore, you can also create subclasses that inherit the properties and methods of the 'User' class, allowing you to extend and specialize the functionality. This promotes code reuse and reduces the need to duplicate code.

Overall, OOP provides a way to organize and structure your code in a modular and reusable manner, making it easier to maintain and update.

2. What are the four principles of OOP and how are they implemented in PHP?

The four pillars of OOP and their PHP implementations:

1. Encapsulation Bundling data and the methods that operate on it within a class, and restricting direct access to internals using visibility modifiers.

class BankAccount {
    private float $balance = 0;

    public function deposit(float $amount): void {
        if ($amount <= 0) throw new InvalidArgumentException('Amount must be positive');
        $this->balance += $amount;
    }

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

PHP 8.4 adds property hooks and asymmetric visibility (public private(set)) as a refined form of encapsulation.

2. Inheritance A class can extend another, inheriting its public and protected properties and methods. Use extends:

class Vehicle { public function move(): string { return 'Moving'; } }
class Car extends Vehicle { public function move(): string { return 'Driving'; } }

3. Polymorphism Objects of different classes respond to the same interface in class-specific ways. In PHP, achieved through method overriding and interface implementation:

interface Shape { public function area(): float; }
class Circle implements Shape { public function area(): float { return M_PI * $this->radius ** 2; } }
class Rectangle implements Shape { public function area(): float { return $this->width * $this->height; } }

4. Abstraction Hiding complex implementation details, exposing only essential interfaces. PHP implements abstraction via:

  • Abstract classes (abstract class) — cannot be instantiated; may contain abstract methods that subclasses must implement.
  • Interfaces — define a contract of method signatures with no implementation.
abstract class Logger {
    abstract protected function write(string $message): void;
    public function log(string $message): void {
        $this->write('[' . date('Y-m-d H:i:s') . '] ' . $message);
    }
}
↑ Back to top

Follow-up 1

Can you explain the concept of Encapsulation with an example?

Encapsulation is the process of hiding the internal details of an object and providing a public interface to interact with it. It helps in achieving data security and code reusability.

Here's an example in PHP:

balance += $amount;
    }

    public function withdraw($amount) {
        if ($amount <= $this->balance) {
            $this->balance -= $amount;
        } else {
            echo 'Insufficient balance.';
        }
    }

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

$account = new BankAccount();
$account->deposit(1000);
$account->withdraw(500);
echo $account->getBalance(); // Output: 500

Follow-up 2

How does Inheritance work in PHP OOP?

Inheritance allows a class to inherit properties and methods from another class. The class that is being inherited from is called the parent class or base class, and the class that inherits is called the child class or derived class.

In PHP, inheritance is implemented using the 'extends' keyword. The child class can access all the public and protected properties and methods of its parent class. It can also override the parent class's methods or add new methods and properties.

Here's an example:

eat(); // Output: The animal is eating.
$dog->bark(); // Output: The dog is barking.

Follow-up 3

What is Polymorphism and how is it used in PHP?

Polymorphism is the ability of objects of different classes to be treated as objects of a common parent class. It allows different objects to respond to the same message in different ways.

In PHP, polymorphism is achieved through method overriding and method overloading.

Method overriding is when a child class defines a method with the same name as a method in its parent class. The child class can provide its own implementation of the method, which will be used instead of the parent class's implementation when the method is called on an object of the child class.

Method overloading is when a class has multiple methods with the same name but different parameters. PHP does not support method overloading by default, but it can be achieved using the magic method '__call'.

Here's an example:

area();
}

// Output:
// Calculating area of circle.
// Calculating area of rectangle.

Follow-up 4

Can you explain the concept of Abstraction in PHP OOP?

Abstraction is the process of simplifying complex systems by breaking them down into smaller, more manageable parts. It focuses on what an object does rather than how it does it.

In PHP, abstraction is implemented using abstract classes and interfaces.

An abstract class is a class that cannot be instantiated and can only be used as a base for other classes. It can contain both abstract and non-abstract methods. Abstract methods are declared without an implementation and must be implemented by any class that extends the abstract class.

An interface is a contract that defines a set of methods that a class must implement. It only contains method signatures and constants, but no implementation. A class can implement multiple interfaces.

Here's an example:

makeSound(); // Output: Woof!
$bird->makeSound(); // Output: Chirp!
$bird->fly(); // Output: The bird is flying.

3. What is the difference between public, private, and protected visibility in PHP OOP?

In PHP OOP, visibility controls where class members (properties and methods) can be accessed from.

public Accessible from anywhere — within the class, from subclasses, and from external code.

class User {
    public string $name = 'Guest'; // readable and writable from anywhere
}
$user = new User();
echo $user->name; // fine

protected Accessible within the class itself and from subclasses. Not accessible from outside the class hierarchy.

class Animal {
    protected string $sound = 'generic';
}
class Dog extends Animal {
    public function speak(): string { return $this->sound; } // OK
}
$a = new Animal();
echo $a->sound; // Fatal error — protected access from outside

private Accessible only within the declaring class. Not accessible from subclasses.

class BankAccount {
    private float $balance = 0;
    public function getBalance(): float { return $this->balance; }
}

PHP 8.4 — Asymmetric visibility PHP 8.4 introduces the ability to set different visibility for read vs write:

class User {
    public private(set) string $name; // readable publicly, writable only within the class
    public function __construct(string $name) { $this->name = $name; }
}
$user = new User('Alice');
echo $user->name;   // OK — public read
$user->name = 'Bob'; // Fatal error — private write

Interview tip: Know why private is preferred over protected for internal implementation details — it prevents subclasses from accidentally depending on or modifying internals, keeping the encapsulation contract stronger.

↑ Back to top

Follow-up 1

Can you provide an example of each?

Sure! Here are examples of each visibility in PHP:

publicProperty; // Output: Public Property
$obj->publicMethod(); // Output: Public Method

// Uncomment the following lines to see the errors
// echo $obj->privateProperty; // Error: Cannot access private property
// $obj->privateMethod(); // Error: Call to private method
// echo $obj->protectedProperty; // Error: Cannot access protected property
// $obj->protectedMethod(); // Error: Call to protected method

Follow-up 2

In what scenarios would you use each of these visibilities?

The choice of visibility depends on the desired level of encapsulation and data hiding in your code. Here are some scenarios where each visibility can be useful:

  • public: Public visibility is used when you want a property or method to be accessible from anywhere. This is useful when you want to expose certain functionality of your class to other parts of your code or external code.

  • private: Private visibility is used when you want to restrict access to a property or method to only within the class itself. This is useful when you have internal implementation details that should not be accessed or modified from outside the class.

  • protected: Protected visibility is used when you want to allow access to a property or method within the class itself and its child classes. This is useful when you have a base class with common functionality that can be extended by child classes, but you still want to restrict access to certain properties or methods.

It's important to carefully choose the appropriate visibility for each property and method to ensure proper encapsulation and maintainability of your code.

4. What are magic methods in PHP OOP and can you provide examples of their use?

Magic methods are special methods with names prefixed by double underscores (__) that PHP calls automatically in response to specific operations on objects. They allow you to customize object behavior.

Most commonly asked magic methods:

class User {
    private array $data = [];

    // Called when object is created
    public function __construct(string $name) {
        $this->data['name'] = $name;
    }

    // Called when accessing an undefined or inaccessible property
    public function __get(string $name): mixed {
        return $this->data[$name] ?? null;
    }

    // Called when assigning to an undefined or inaccessible property
    public function __set(string $name, mixed $value): void {
        $this->data[$name] = $value;
    }

    // Called when isset() or empty() used on inaccessible property
    public function __isset(string $name): bool {
        return isset($this->data[$name]);
    }

    // Called when object is used as a string (e.g., echo $obj)
    public function __toString(): string {
        return json_encode($this->data);
    }

    // Called when object is invoked as a function
    public function __invoke(string $greeting): string {
        return "$greeting, {$this->data['name']}!";
    }

    // Called when object is destroyed / goes out of scope
    public function __destruct() {
        // cleanup
    }
}

// Additional important magic methods:
// __clone()      — called when object is cloned with clone keyword
// __serialize()  — PHP 8.1+, custom serialization
// __unserialize() — PHP 8.1+, custom deserialization
// __debugInfo()  — controls var_dump() output

Interview note: Overusing magic methods (especially __get/__set) can hurt IDE auto-complete and static analysis. PHP 8.4 property hooks offer a typed, analyzable alternative.

↑ Back to top

Follow-up 1

Can you explain the use of __get() and __set() methods?

The __get() and __set() methods are magic methods in PHP that are used to define custom logic for accessing and modifying inaccessible or non-existent properties of an object.

  • __get(): This method is called when an inaccessible or non-existent property is accessed. It receives the name of the property as an argument and should return the value of the property. Here is an example:
class MyClass {
    private $name;

    public function __get($property) {
        if ($property === 'name') {
            return $this->name;
        }
    }
}

$obj = new MyClass();
$obj->name = 'John';
echo $obj->name;
// Output: John
  • __set(): This method is called when an inaccessible or non-existent property is assigned a value. It receives the name of the property and the value as arguments and should handle the assignment. Here is an example:
class MyClass {
    private $name;

    public function __set($property, $value) {
        if ($property === 'name') {
            $this->name = $value;
        }
    }
}

$obj = new MyClass();
$obj->name = 'John';
echo $obj->name;
// Output: John

Follow-up 2

What is the __construct() method and when is it called?

The __construct() method is a magic method in PHP that is automatically called when an object is created from a class. It is commonly used for initialization tasks, such as setting default property values or establishing database connections. Here is an example of how the __construct() method can be used:

class MyClass {
    private $name;

    public function __construct($name) {
        $this->name = $name;
        echo 'Object created with name: ' . $this->name;
    }
}

$obj = new MyClass('John');
// Output: Object created with name: John

Follow-up 3

What is the purpose of the __destruct() method?

The __destruct() method is a magic method in PHP that is automatically called when an object is no longer referenced or when the script ends. It is commonly used for cleanup tasks, such as closing database connections or releasing resources. Here is an example of how the __destruct() method can be used:

class MyClass {
    private $connection;

    public function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    }

    public function __destruct() {
        $this->connection = null;
        echo 'Object destroyed and database connection closed.';
    }
}

$obj = new MyClass();
// Output: Object destroyed and database connection closed.

5. What is the concept of 'Interfaces' in PHP OOP?

An interface in PHP defines a contract — a set of method signatures that any implementing class must provide. Interfaces contain no implementation code (except default method implementations are not allowed in PHP, unlike Java); they only declare what methods must exist.

interface Serializable {
    public function serialize(): string;
    public function unserialize(string $data): void;
}

class User implements Serializable {
    public function __construct(private string $name) {}

    public function serialize(): string {
        return json_encode(['name' => $this->name]);
    }

    public function unserialize(string $data): void {
        $this->name = json_decode($data, true)['name'];
    }
}

Key characteristics:

  • All methods declared in an interface are implicitly public.
  • A class can implement multiple interfaces (PHP does not support multiple class inheritance).
  • Interfaces can extend other interfaces.
  • Interface constants are supported; PHP 8.3 added typed interface constants.
interface Logger extends Stringable {
    const string DEFAULT_CHANNEL = 'app';
    public function log(string $level, string $message): void;
}

Interfaces vs Abstract Classes:

Feature Interface Abstract Class
Implementation None allowed Some allowed
Multiple inheritance Yes (implement many) No (extend one)
Properties No (only constants) Yes
Constructor No Yes
Use case Define a capability/contract Share base implementation

Interview note: Dependency injection and type-hinting against interfaces (not concrete classes) is a core principle of SOLID design — it enables swapping implementations without changing client code.

↑ Back to top

Follow-up 1

How does an interface differ from a class?

An interface in PHP differs from a class in the following ways:

  • An interface cannot be instantiated directly, whereas a class can be.
  • An interface can only contain method signatures, constants, and static methods, whereas a class can contain properties, methods, and other members.
  • A class can implement multiple interfaces, but it can only inherit from a single class.
  • An interface does not provide any implementation details, whereas a class can provide the implementation for its methods.

Follow-up 2

Can you provide an example of the use of interfaces?

Sure! Here's an example of how interfaces can be used in PHP:

interface Shape {
    public function calculateArea();
}

class Circle implements Shape {
    private $radius;

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

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

class Rectangle implements Shape {
    private $length;
    private $width;

    public function __construct($length, $width)
    {
        $this->length = $length;
        $this->width = $width;
    }

    public function calculateArea()
    {
        return $this->length * $this->width;
    }
}

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

$rectangle = new Rectangle(4, 6);
echo $rectangle->calculateArea(); // Output: 24

Follow-up 3

What is the purpose of using interfaces?

The purpose of using interfaces in PHP is to enforce a contract between classes. By implementing an interface, a class is required to provide the implementation for all the methods defined in the interface. This allows for better code organization, modularity, and reusability. Interfaces also enable polymorphism, where objects of different classes can be treated as instances of a common interface, allowing for more flexible and extensible code.

Live mock interview

Mock interview: PHP OOP

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.