PHP Classes And Objects


Object-oriented programming (OOP) is a paradigm used in PHP to structure and organize code into reusable components called classes and objects. Classes define the blueprint for objects, while objects are instances of classes. Understanding OOP concepts in PHP is crucial for writing maintainable, scalable, and efficient code. This article covers common interview questions and answers related to PHP classes and objects.


What is a class in PHP?

Answer:
A class in PHP is a blueprint or template for creating objects. It defines properties (variables) and methods (functions) that an object can have. In object-oriented programming (OOP), a class is used to encapsulate data and behavior.

Example:

class Car {
   public $color;
   public $model;
   public function setColor($color) {
      $this->color = $color;
   }
}

What is an object in PHP?

Answer:
An object is an instance of a class. When you create an object, you are instantiating a class, which allows you to access its properties and methods.

Example:

$myCar = new Car(); // Creating an object of class Car
$myCar->setColor("Red");

How do you define a class in PHP?

Answer:
You define a class in PHP using the class keyword, followed by the class name and a block of code containing its properties and methods.

Example:

class Car {
   public $make;
   public $model;
   public function setModel($model) {
      $this->model = $model;
   }
}

How do you create an object in PHP?

Answer:
You create an object by instantiating a class using the new keyword.

Example:

$car = new Car(); // Creating an object of the Car class
$car->setModel("Toyota");

What is a constructor in PHP?

Answer:
A constructor is a special method in a class that is automatically called when an object of that class is instantiated. In PHP, constructors are defined using the __construct() method. They are typically used to initialize object properties.

Example:

class Car {
   public $make;
   public function __construct($make) {
      $this->make = $make;
   }
}
$car = new Car("Toyota");
echo $car->make; // Outputs: Toyota

What is the $this keyword in PHP?

Answer:
The $this keyword is used within a class to refer to the current instance of the class. It allows you to access the object’s properties and methods.

Example:

class Car {
   public $model;
   public function setModel($model) {
      $this->model = $model; // Using $this to reference the current object
   }
}
$car = new Car();
$car->setModel("Honda");

What are access modifiers in PHP?

Answer:
Access modifiers define the visibility of class properties and methods. PHP supports three access modifiers:

  • public: Accessible from anywhere.
  • protected: Accessible only within the class and its subclasses.
  • private: Accessible only within the class where they are defined.

Example:

class Car {
   public $model; // Accessible anywhere
   protected $year; // Accessible in the class and subclasses
   private $owner; // Accessible only within the class
}

What is inheritance in PHP?

Answer:
Inheritance allows a class (called a child or subclass) to inherit properties and methods from another class (called a parent or superclass). This promotes code reuse and logical hierarchy.

Example:

class Vehicle {
   public $type;
   public function setType($type) {
      $this->type = $type;
   }
}
class Car extends Vehicle {
   public $model;
   public function setModel($model) {
      $this->model = $model;
   }
}
$car = new Car();
$car->setType("Sedan");
$car->setModel("Toyota");

What is method overriding in PHP?

Answer:
Method overriding occurs when a subclass provides its own implementation of a method that is already defined in its parent class. The overridden method in the child class replaces the parent's version.

Example:

class Vehicle {
   public function startEngine() {
      echo "Starting the vehicle engine.";
   }
}
class Car extends Vehicle {
   public function startEngine() {
      echo "Starting the car engine."; // Overriding the parent method
   }
}
$car = new Car();
$car->startEngine(); // Outputs: Starting the car engine.

What is method overloading in PHP?

Answer:
PHP does not natively support method overloading (i.e., multiple methods with the same name but different parameters). However, you can simulate method overloading by using variable arguments with func_num_args(), func_get_arg(), or using type checks in the method body.

Example using func_num_args():

class Calculator {
   public function add() {
      $numArgs = func_num_args();
      if ($numArgs == 2) {
         return func_get_arg(0) + func_get_arg(1);
      } elseif ($numArgs == 3) {
         return func_get_arg(0) + func_get_arg(1) + func_get_arg(2);
      }
   }
}
$calc = new Calculator();
echo $calc->add(1, 2); // Outputs: 3
echo $calc->add(1, 2, 3); // Outputs: 6

What is an abstract class in PHP?

Answer:
An abstract class is a class that cannot be instantiated and is meant to be extended by other classes. It can have abstract methods, which are methods that must be implemented by the child classes.

Example:

abstract class Vehicle {
   abstract public function startEngine(); // Abstract method
}
class Car extends Vehicle {
   public function startEngine() {
      echo "Car engine started."; // Implementation of abstract method
   }
}
$car = new Car();
$car->startEngine();

What is an interface in PHP?

Answer:
An interface defines a contract for classes to implement. It contains method signatures but no method bodies. A class that implements an interface must provide implementations for all its methods.

Example:

interface Drivable {
   public function startEngine();
}
class Car implements Drivable {
   public function startEngine() {
      echo "Car engine started.";
   }
}
$car = new Car();
$car->startEngine();

What is the difference between an abstract class and an interface in PHP?


Answer:

  • Abstract class: Can have both abstract and concrete methods. It allows you to define default behavior while forcing subclasses to implement certain methods. A class can only extend one abstract class.
  • Interface: Contains only method signatures without implementation. A class can implement multiple interfaces, providing more flexibility for complex designs.

What is polymorphism in PHP?

Answer:
Polymorphism allows objects of different classes to be treated as objects of a common superclass or interface. It enables the same method to have different implementations in various classes.

Example:

interface Animal {
   public function makeSound();
}
class Dog implements Animal {
   public function makeSound() {
      echo "Bark!";
   }
}
class Cat implements Animal {
   public function makeSound() {
      echo "Meow!";
   }
}
$animals = [new Dog(), new Cat()];
foreach ($animals as $animal) {
   $animal->makeSound(); // Outputs: Bark! Meow!
}

What is a static property or method in PHP?

Answer:
A static property or method belongs to the class itself rather than to a specific object. Static methods and properties can be accessed without creating an instance of the class.

Example:

class Math {
   public static $pi = 3.1416;
   public static function multiply($a, $b) {
      return $a * $b;
   }
}
echo Math::$pi; // Accessing static property
echo Math::multiply(2, 3); // Accessing static method

What is the final keyword in PHP?

Answer:
The final keyword prevents a class from being extended or a method from being overridden by subclasses.

Example:

final class Vehicle {
   // This class cannot be extended
}
class Car {
   final public function startEngine() {
      echo "Starting engine."; // This method cannot be overridden
   }
}

What is the __destruct() method in PHP?

Answer:
The __destruct() method is a destructor in PHP that is called when an object is destroyed. It is typically used to perform cleanup tasks, such as closing database connections or freeing resources.

Example:

class Car {
   public function __destruct() {
      echo "Destroying the Car object.";
   }
}
$car = new Car();
unset($car); // Destructor will be called here

What are magic methods in PHP?

Answer:
Magic methods are special methods in PHP that are called automatically in certain situations. They start with __ (double underscore). Common magic methods include:

  • __construct(): Called when an object is created.
  • __destruct(): Called when an object is destroyed.
  • __call(): Invoked when calling inaccessible or undefined methods.
  • __get(): Invoked when accessing inaccessible or undefined properties.
  • __set(): Invoked when setting inaccessible or undefined properties.

Example of __get() and __set():

class Car {
   private $data = [];
   public function __set($name, $value) {
      $this->data[$name] = $value;
   }
   public function __get($name) {
      return $this->data[$name];
   }
}
$car = new Car();
$car->model = "Honda"; // __set() is called
echo $car->model; // __get() is called

What is __autoload() or spl_autoload_register() in PHP?

Answer:
The __autoload() function was used to automatically load classes when they are instantiated, but it has been deprecated in favor of spl_autoload_register(). spl_autoload_register() allows you to register multiple autoload functions to handle class loading.

Example:

spl_autoload_register(function($className) {
   include $className . ".php"; // Automatically includes the class file
});
$car = new Car(); // Automatically loads Car.php

What is a trait in PHP?

Answer:
A trait in PHP is a mechanism for code reuse. It allows you to group methods that can be used in multiple classes. Traits solve the issue of single inheritance by allowing you to include functionality from multiple sources.

Example:

trait Driveable {
   public function drive() {
      echo "Driving the car.";
   }
}
class Car {
   use Driveable; // Using the trait in the class
}
$car = new Car();
$car->drive(); // Outputs: Driving the car.
Ads