PHP Interview Question 2

6.What are Traits?

Traits are a mechanism for code reuse in single inheritance languages like PHP.

They let you group methods in a reusable unit independent of class hierarchy.

You can think of traits as a mixin: reusable bits of functionality injected into classes.

 

trait Logger {
    public function log($message) {
        echo "[LOG]: $message";
    }
}

 

class User {
    use Logger;
}
$user = new User();
$user->log("User created."); // Outputs: [LOG]: User created.

7.Why Use Traits?

  • To avoid code duplication.
  • When multiple classes need the same method, but there's no natural parent-child relationship.
  • To compose behaviors without multiple inheritance.
trait A {
    public function sayHello() {
        echo "Hello from A";
    }
}
trait B {
    public function sayHello() {
        echo "Hello from B ";
    }
}
class Test {
    use A, B {
        B::sayHello insteadof A;
        A::sayHello as sayHelloFromA;
    }
}
$test = new Test();
$test->sayHello();
$test->sayHelloFromA();// Outputs: Hello from B Hello from A

8.How does PHP's garbage collection work?

PHP's garbage collection (GC) is designed to free up memory by automatically destroying variables or objects that are no longer in use, especially when they are involved in circular references.

1. Reference Counting

PHP uses reference counting to manage memory:

  • Every variable has a refcount (reference count).
  • When a variable is assigned, the count increases.
  • When a variable goes out of scope or is unset, the count decreases.
  • When the count reaches zero, PHP frees the memory.
$a = new stdClass();
$b = $a; // refcount = 2
unset($a); // refcount = 1
unset($b); // refcount = 0, memory freed

 

2. Problem with Circular References

Reference counting fails in circular references (objects referencing each other):

$a = new stdClass();
$b = new stdClass();
$a->ref = $b;
$b->ref = $a;

Even after unset($a) and unset($b), memory isn’t released because both still "refer" to each other.


3. Garbage Collector for Circular References

To handle this, PHP uses a cycle collector based on the "root buffer" algorithm (since PHP 5.3+):

  • It periodically scans objects that are possibly in cycles.
  • If it detects a circular reference and confirms no external references, it collects and frees the memory.

You can control the garbage collector with:

gc_enable();     // Enable GC (default is on)
gc_disable();    // Disable GC
gc_collect_cycles(); // Manually trigger GC
 
class A {
    public $ref;
}
gc_enable(); // Make sure garbage collection is on
 
echo "GC cycles before: " . gc_collect_cycles() . PHP_EOL."<br/>";
 
// Create circular reference
$a = new A();
$b = new A();
$a->ref = $b;
$b->ref = $a;
// Break direct access
unset($a);
unset($b);
 
// At this point, memory is still not freed due to the circular reference and Manually trigger garbage collection
echo "GC cycles after unset (before collection): " . gc_collect_cycles() . PHP_EOL."<br/>";
echo "GC cycles collected: ".gc_collect_cycles(). PHP_EOL;

 

Output (example):

GC cycles before: 0
GC cycles after unset (before collection): 2
GC cycles collected: 0



9.What are the key principles of OOP in PHP?

The key principles of Object-Oriented Programming (OOP) in PHP are centered around 4 core concepts: Encapsulation, Inheritance, Polymorphism, and Abstraction. Here’s a breakdown with PHP examples:

1. Encapsulation

  • Bundles data (properties) and behavior (methods) into a single unit (class).
  • Restricts direct access using public, protected, and private.
class User {
    private $name;
 
    public function setName($name) {
        $this->name = $name;
    }
 
    public function getName() {
        return $this->name;
    }
}
 
$user = new User();
$user->setName("John");
echo $user->getName(); // John

 

2. Inheritance

  • A class (child) can inherit properties and methods from another class (parent).
class Animal {
    public function speak() {
        return "Sound";
    }
}
 
class Dog extends Animal {
    
}
$dog = new Dog();
echo $dog->speak(); // Sound


3. Polymorphism

  • Objects of different classes can be treated as instances of the same parent class, especially when using interfaces or abstract classes (method overriding).
interface Shape {
    public function draw();
}
 
class Circle implements Shape {
    public function draw() {
        return "Drawing Circle";
    }
}
 
class Square implements Shape {
    public function draw() {
        return "Drawing Square";
    }
}
 
function renderShape(Shape $shape) {
    echo $shape->draw();
}
$shape = new Square();
renderShape($shape); // Drawing Square


4. Abstraction

  • Defines the what but not the how. Achieved via abstract classes and interfaces.
abstract class Vehicle {
    abstract public function startEngine();
}
 
class Car extends Vehicle {
    public function startEngine() {
        echo "Car engine started";
    }
}
$car = new Car();
$car->startEngine();

10. Difference between abstract class and interface?

In PHP, abstract classes and interfaces are both used to define the structure of classes, but they have key differences in behavior and use cases:

Abstract Class

  • Can have both abstract methods (no body) and concrete methods (with body).
  • Can define properties (variables).
  • Use abstract keyword.
  • A class can only extend one abstract class (single inheritance).
abstract class Animal {
	public $name;
	abstract public function makeSound();
	public function sleep() {
	  echo "Sleeping...";
	}
}

class Dog extends Animal {
	public function makeSound() {
	  echo "Bark!";
	}
}
$dog = new Dog();         // Create Dog object
$dog->name = "Buddy";     // Set name
echo $dog->name;          // Get name -> Output: Buddy
$dog->makeSound();        // Output: Bark!
$dog->sleep();           // Output: Sleeping...

 

Interface

  • Can only contain method declarations (no body) until PHP 8.0 (which introduced limited method bodies).
  • Cannot have properties (only constants).
  • Use interface keyword.
  • A class can implement multiple interfaces (multiple inheritance).
interface Logger {
    public function log($message);
}

interface Notifier {
    public function notify($user);
}

class App implements Logger, Notifier {
	public function log($message) {
	    echo "Log: $message <br/>";
	}
	public function notify($user) {
	    echo "Notify: $user";
	}
}

$app = new App();
$app->log("message1");
$app->log("user");

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.