PHP OOPs Interview Questions & Answers

PHP OOP interview questions: class and object, constructor, public, private and protected, static, traits, magic methods, abstract class vs interface and final class.

How to create a class and object in PHP?

To create a class in PHP, use the class keyword followed by the class name. A class is like a blueprint, and an object is a real thing made from that blueprint using the new keyword.

Inside a class you can keep variables (called properties) and functions (called methods).

<?php
class Student {
    public $name;

    public function sayHello() {
        return "Hello, my name is " . $this->name;
    }
}

// Create an object using the new keyword
$student1 = new Student();
$student1->name = "Robin";

echo $student1->sayHello();
?>

Output:

Tutorials Class - Output Window

Hello, my name is Robin

You can create many objects from same class, and each object keeps its own values. Read more in PHP Class and PHP OOP Introduction.

What is the difference between public, private and protected in PHP?

public, protected and private are access modifiers (also called visibility). They decide who can use a property or a method of a class.

KeywordCan be accessed from
publicAnywhere: inside the class, in child classes and outside the class
protectedInside the class and in its child classes only
privateInside the same class only
<?php
class Account {
    public $name = "Robin";
    protected $type = "Savings";
    private $pin = 1234;
}

$acc = new Account();

echo $acc->name;   // works, it is public
// echo $acc->pin; // Fatal error, private property can not be accessed outside
?>

Output:

Tutorials Class - Output Window

Robin

If you try to read a private or protected property from outside the class, PHP stops with a fatal error. To give controlled access, we normally write public methods (getters and setters) inside the class.

Note: The words transient and volatile are from Java, they do not exist in PHP.

Is multiple inheritance supported in PHP?

No. PHP does not support multiple inheritance for classes. A class can extend only one parent class, so class C extends A, B gives an error.

But there are two ways to get similar result:

  • Interfaces: a class can implement many interfaces.
  • Traits: a class can use many traits to reuse code. See What are traits in PHP?.
<?php
interface Logger {
    public function log($msg);
}

interface Mailer {
    public function send($to);
}

class Notifier implements Logger, Mailer {
    public function log($msg) {
        echo "Log: " . $msg . "<br>";
    }

    public function send($to) {
        echo "Mail sent to " . $to;
    }
}

$n = new Notifier();
$n->log("Notifier started");
$n->send("robin@example.com");
?>

Output:

Tutorials Class - Output Window

Log: Notifier started
Mail sent to robin@example.com

Multilevel inheritance (C extends B, and B extends A) is supported, only multiple parents at same time is not.

What is the meaning of final class and final method in PHP?

The final keyword is used to stop inheritance. If a class is marked final, no other class can extend it. If a method is marked final, child classes can not override it.

<?php
class Base {
    final public function show() {
        echo "This method can not be changed";
    }
}

class Child extends Base {
    // Writing show() here would give a fatal error
}

$c = new Child();
$c->show();
?>

Output:

Tutorials Class - Output Window

This method can not be changed

A final class is written like this:

<?php
final class Util {
    public static function version() {
        return "1.0";
    }
}

// class Other extends Util {}  // Fatal error: a final class can not be extended
?>

When to use it: when a class or method must not be changed, for example a security check or a core logic. Note that properties can not be final, but from PHP 8.1 you can use readonly for properties that must not change after setting.

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

Both abstract class and interface are used to force child classes to follow a structure. But they are used for different purposes.

An abstract class is a partly built class. It can have normal methods with code and abstract methods without code. An interface is only a contract: it lists the methods that a class must have.

FeatureAbstract classInterface
Keywordabstract class and extendsinterface and implements
Method with codeYesNo, only method names
PropertiesYesNo (only constants)
InheritanceA class can extend only oneA class can implement many
Method visibilitypublic, protected or privatepublic only
Best used forSharing common code between related classesGiving same rules to unrelated classes
<?php
abstract class Shape {
    abstract public function area();

    public function describe() {
        return "Area is " . $this->area();
    }
}

class Square extends Shape {
    private $side;

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

    public function area() {
        return $this->side * $this->side;
    }
}

$sq = new Square(4);
echo $sq->describe();
?>

Output:

Tutorials Class - Output Window

Area is 16

You can not create an object of an abstract class or an interface directly. Only the child class that completes all methods can be used to create objects.

What are traits in PHP?

A trait is a group of methods that you can reuse in many classes. It is a way to share code between classes that are not related, and it helps to solve the problem of no multiple inheritance in PHP.

You create a trait with the trait keyword and add it to a class using the use keyword.

<?php
trait Hello {
    public function sayHello() {
        echo "Hello ";
    }
}

trait World {
    public function sayWorld() {
        echo "World";
    }
}

class Greeting {
    use Hello, World;
}

$g = new Greeting();
$g->sayHello();
$g->sayWorld();
?>

Output:

Tutorials Class - Output Window

Hello World

  • A class can use many traits.
  • You can not create an object of a trait directly.
  • If two traits have a method with the same name, PHP gives an error. You can solve it with the insteadof keyword.

What is a constructor in PHP?

A constructor is a special method that runs automatically when an object is created. In PHP it is written as __construct(). It is mostly used to set the starting values of the object.

A destructor, written as __destruct(), is the opposite. It runs when the object is destroyed, or when the script ends.

<?php
class Student {
    public $name;

    public function __construct($name) {
        $this->name = $name;
        echo "Object created for " . $name . "<br>";
    }

    public function __destruct() {
        echo "Object for " . $this->name . " is destroyed";
    }
}

$s = new Student("Robin");
echo "Script is running...<br>";
?>

Output:

Tutorials Class - Output Window

Object created for Robin
Script is running…
Object for Robin is destroyed

From PHP 8.0 you can write a shorter constructor using constructor property promotion. The property is declared and set in the constructor line itself.

<?php
class Student {
    public function __construct(public string $name) {}
}

$s = new Student("Robin");
echo $s->name;
?>

Output:

Tutorials Class - Output Window

Robin

What is the use of the static keyword in PHP?

The static keyword has two main uses in PHP: inside classes, and inside functions.

1. Static property and method. They belong to the class itself, not to an object. You can use them without creating an object, with the double colon (::).

<?php
class Counter {
    public static $count = 0;

    public static function increase() {
        self::$count++;
    }
}

Counter::increase();
Counter::increase();

echo Counter::$count;
?>

Output:

Tutorials Class - Output Window

2

2. Static variable in a function. A normal variable is deleted when the function ends. A static variable keeps its value between function calls.

<?php
function visit() {
    static $n = 0;
    $n++;
    echo $n . " ";
}

visit();
visit();
visit();
?>

Output:

Tutorials Class - Output Window

1 2 3

Remember that a static method can not use $this, because there is no object.

What is the difference between $this, self and static in PHP?

These three keywords are used inside a class, but they point to different things.

KeywordWhat it meansUsed for
$thisThe current objectNormal properties and methods
selfThe class where the code is writtenStatic properties, constants and static methods
staticThe class that was actually called (late static binding)Static methods when child classes are involved
<?php
class Car {
    public $name = "Swift";
    public static $wheels = 4;

    public function show() {
        return $this->name . " has " . self::$wheels . " wheels";
    }
}

$car = new Car();
echo $car->show();
?>

Output:

Tutorials Class - Output Window

Swift has 4 wheels

The difference between self and static is seen when a child class calls the method.

<?php
class A {
    public static function create() {
        return new static();   // self would always create class A
    }
}

class B extends A {}

echo get_class(B::create());
?>

Output:

Tutorials Class - Output Window

B

If we had written new self(), the output would be A.

What are magic methods in PHP?

Magic methods are special methods in PHP classes. Their names start with a double underscore (__). PHP calls them automatically in some situations, you do not call them yourself.

MethodWhen PHP calls it
__construct()When an object is created
__destruct()When an object is destroyed
__get($name)When reading a property that is not accessible or does not exist
__set($name, $value)When writing to a property that is not accessible or does not exist
__call($name, $args)When calling a method that does not exist
__toString()When an object is used as a string, for example with echo
__invoke()When an object is called like a function
<?php
class User {
    private $data = ["name" => "Robin"];

    public function __get($key) {
        return $this->data[$key] ?? "Not found";
    }

    public function __toString() {
        return "User: " . $this->data["name"];
    }
}

$u = new User();
echo $u->name . "<br>";
echo $u->city . "<br>";
echo $u;
?>

Output:

Tutorials Class - Output Window

Robin
Not found
User: Robin

Do not create your own methods with a double underscore name, because PHP keeps these names for itself.