PHP OOPs Interview Questions and Answers
Ques 16. What is a trait in PHP?
A trait is similar to a class but intended to group functionality in a fine-grained and consistent way. Traits are used to declare methods in a class.
Example:
trait Loggable {
public function log($message)
{
echo $message;
}
}
class User {
use Loggable;
}
Ques 17. What is the difference between an abstract class and an interface?
An abstract class can have both abstract and non-abstract methods, and it can have properties. Interfaces can only have abstract methods and constants.
Ques 18. Explain late static binding in PHP.
Late static binding allows static methods to reference the called class using the 'static' keyword. It helps resolve the class at runtime rather than at compile time.
Example:
class ParentClass {
public static function whoAmI() {
echo static::class;
}
}
class ChildClass extends ParentClass { }
ChildClass::whoAmI(); // Outputs 'ChildClass'
Ques 19. What is the use of the 'self' keyword in PHP?
The 'self' keyword is used to refer to the current class. It is used to access static properties and methods within the class itself.
Example:
class Example {
private static $counter = 0;
public static function incrementCounter() {
self::$counter++;
}
}
Ques 20. Explain the Singleton design pattern in PHP.
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It involves a private constructor and a static method to get the instance.
Example:
class Singleton {
private static $instance;
private function __construct() { /* private constructor */ } public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
Most helpful rated by users: