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

This is the second and final part of the OOP interview question and answer series.

1. What is Trait ? Explain with an example?

A trait in PHP is a way to group reusable methods and properties. Traits can be used to share code between classes without having to inherit from them.

Traits are declared using the trait keyword. The following code shows an example of a trait:

trait Logger {
    public function log($message) {
        echo "Logging message: $message";
    }
}

The Logger trait defines a single method, log(). The log() method can be used to log messages to the console.

Traits can be used in classes using the use keyword. The following code shows an example of how to use the Logger trait in a class:

$animal = new Animal();
$animal->log("I am an animal!"); // Logging message: I am an animal!

The output of the code is “Logging message: I am an animal!”.

Traits can be a powerful tool for writing reusable code. By using traits, you can avoid duplicating code in multiple classes.

2. What is Namespace ? How we can create and use Namespace in PHP ?

Namespaces in PHP are a way to organize code into logical groups. This can help to prevent name collisions and make code easier to read and understand.

Namespaces are declared using the namespace keyword. The following code shows an example of a namespace declaration:

namespace My\App;

The My\App namespace declares a namespace called My\App. This namespace can be used to organize code that belongs to the My\App application.

Classes, functions, and constants can be declared within a namespace using the use keyword. The following code shows an example of how to use the use keyword to import a class from a namespace:

use My\App\Animal;

$animal = new Animal();

The use keyword tells PHP to import the Animal class from the My\App namespace. We can then create a new instance of the Animal class using the new keyword.

Namespaces can be nested, which means that you can create namespaces within namespaces. The following code shows an example of a nested namespace:

namespace My\App\Animals;

class Dog {
}

3. What is the use of final keyword in PHP ?

The final keyword in PHP is used to prevent a class, method, or property from being inherited, overridden, or accessed directly. This can be useful for a variety of reasons, such as:

  • Preventing inheritance: The final keyword can be used to prevent a class from being inherited. This can be useful if you want to ensure that the class cannot be modified by other developers. For example, you might use the final keyword to prevent a class from being extended with new features that could potentially break the code.
  • Preventing method overriding: The final keyword can be used to prevent a method from being overridden by a subclass. This can be useful if you want to ensure that the method cannot be changed by other developers. For example, you might use the final keyword to prevent a method from being modified with new functionality that could potentially break the code.
  • Preventing direct access to properties: The final keyword can be used to prevent a property from being accessed directly. This can be useful if you want to ensure that the property can only be accessed through the class’s methods. For example, you might use the final keyword to prevent a property from being modified directly, which could potentially break the code.

Here are some examples of how the final keyword can be used in PHP:

// Prevent inheritance
final class Animal {
}

// Prevent method overriding
final class Dog extends Animal {
    public function bark() {
        return "Woof!";
    }
}

// Prevent direct access to properties
final class Cat {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

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

$dog = new Dog();
// $dog->bark(); // Error: Cannot override final method Animal::bark()

$cat = new Cat();
$cat->name = "Simba";
// $cat->name = "Mufasa"; // Error: Cannot modify private property Cat::$name

4. What are access modifiers in PHP? Explain with some examples

Access modifiers in PHP are keywords that control the visibility of classes, methods, and properties. There are three access modifiers in PHP:

  • public: The public access modifier makes a class, method, or property visible to everyone. This is the default access modifier in PHP.
  • protected: The protected access modifier makes a class, method, or property visible to the class itself and its subclasses.
  • private: The private access modifier makes a class, method, or property visible only to the class itself.

Here are some examples of how access modifiers can be used in PHP:

// A public class
class Animal {
    public function speak() {
        return "I am an animal!";
    }
}

// A protected method
class Dog extends Animal {
    protected function bark() {
        return "Woof!";
    }
}

// A private property
class Cat extends Animal {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

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

$animal = new Animal();
echo $animal->speak(); // I am an animal!

$dog = new Dog();
// $dog->bark(); // Error: Cannot access protected method Dog::bark()

$cat = new Cat();
$cat->name = "Simba";
echo $cat->name; // Simba

5. What are the different types of constructors in PHP ?

There are two types of constructors in PHP:

  • Default constructor: The default constructor is called when a new object is created from a class. The default constructor does not have any parameters.
  • Parameterized constructor: The parameterized constructor is called when a new object is created from a class and it has parameters. The parameterized constructor can be used to initialize the object’s properties with the values passed in as parameters.

Here is an example of a default constructor in PHP:

class Animal {
    public function __construct() {
        // Do something when the object is created
    }
}

$animal = new Animal();

This code will create a new Animal object and call the default constructor. The default constructor does not do anything, but it could be used to initialize the object’s properties.

Here is an example of a parameterized constructor in PHP:

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

$animal = new Animal("Simba", 10);

This code will create a new Animal object and call the parameterized constructor. The parameterized constructor will initialize the object’s name property to Simba and the object’s age property to 10.

Along with this there is a third type of constructor in PHP which doesn’t use the __construct keyword but useful in many instances known as copy constructor. Instead of defining lets understand it with a scenario : Let’s say if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy. This is the best use case of copy constructor. An object copy is created by using the clone keyword

$copy_of_object = clone $object;

When an object is cloned, PHP will perform a shallow copy of all of the object’s properties. Any properties that are references to other variables will remain references.

Here is an example

class MyClass {

    private $myArray = array();
    function pushSomethingToArray($var) {
        array_push($this->myArray, $var);
    }
    function getArray() {
        return $this->myArray;
    }

}

//push some values to the myArray of Mainclass
$myObj = new MyClass();
$myObj->pushSomethingToArray('blue');
$myObj->pushSomethingToArray('orange');
$myObjClone = clone $myObj;
$myObj->pushSomethingToArray('pink');

//testing
print_r($myObj->getArray());     //Array([0] => blue,[1] => orange,[2] => pink)
print_r($myObjClone->getArray());//Array([0] => blue,[1] => orange)
//so array  cloned 

6. What are the differences between Abstract Class and Interface in PHP ?

Abstract classes and interfaces are both used to achieve polymorphism in PHP. However, they have different purposes and use cases.

  • Abstract classes are used to define common functionality that can be inherited by subclasses. Abstract classes cannot be instantiated directly. They must be subclassed and the subclass must provide implementations for the abstract methods in the parent class.
  • Interfaces are used to define contracts that classes must implement. Interfaces can be implemented by multiple classes. Interfaces do not define any functionality themselves. They only define the methods that must be implemented by the classes that implement the interface.

Let’s find out the difference between them

FeatureAbstract ClassInterface
NatureCan have both abstract (without implementation) and non-abstract (with implementation) methods.Only abstract methods. Modern languages allow default implementations (e.g., PHP 8, Java 8).
InheritanceA class can extend only one abstract class (single inheritance).A class can implement multiple interfaces.
Access ModifiersCan have methods with public, protected, and private modifiers.Typically methods are public. Some languages restrict other modifiers.
VariablesCan have instance variables (static and non-static).Can have constants. No instance variables.
ConstructorCan have constructors for initialization tasks.Cannot have constructors.
Relationship IndicationOften indicates an “is-a” relationship. Subclasses are more specific types of the superclass.Indicates a capability or role the class should fulfill.
FlexibilityCan share common implementation among subclasses.Extends the capabilities of a class in a flexible manner.

7. What is a class constant in PHP ? Can we redefine class constant in child class ?

A class constant is a constant value associated with a class (or an interface). Unlike class variables, the value of a class constant cannot change after it’s defined. These constants are useful when you want to define some fixed data or configuration that relates to a class and should remain unmodifiable.

class Circle {
    // class constant declaration
    const PI = 3.14159265359;

    private $radius;

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

    public function area() {
        // using class constant in a method
        return self::PI * $this->radius * $this->radius;
    }
}

// Accessing class constant from outside the class
echo "Value of PI: " . Circle::PI . "\n";

$circle = new Circle(5);
echo "Area of circle with radius 5: " . $circle->area() . "\n";

In the example above:

  • PI is a class constant for the Circle class.
  • We access the PI constant using Circle::PI from outside the class and self::PI from inside the class.
  • Even though we can technically access the class constant using an object instance (e.g., $circle::PI), it’s more conventional and clearer to use the class name.

Some points to remember regarding class constants

  1. Declaration: Class constants are declared using the const keyword inside a class or interface.
  2. Access: They are always publicly accessible, regardless of where they are defined. You don’t use the $ symbol to reference or define them.
  3. Scope: You reference them using the class name followed by the scope resolution operator (::), or by using an object instance, though the latter is less common for constants.
  4. Visibility: You can also use the access modifiers with class constants as of PHP version 7.1.0

Another important point to remember here

it’s possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by ‘get_called_class‘ method:

abstract class dbObject
{    
    const TABLE_NAME='undefined';
    
    public static function GetAll()
    {
        $c = get_called_class();
        return "SELECT * FROM `".$c::TABLE_NAME."`";
    }    
}

class dbPerson extends dbObject
{
    const TABLE_NAME='persons';
}

class dbAdmin extends dbPerson
{
    const TABLE_NAME='admins';
}

echo dbPerson::GetAll()."<br>";//"SELECT * FROM `persons`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"

8. What are magic methods in PHP ?

Magic methods are special methods which override PHP’s default’s action when certain actions are performed on an object.

Some of the magic methods are

 __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset()

Previous post Most asked Object Oriented Interview Questions in PHP – Part -1
Trait Next post All you need to know about Traits in PHP