PHP OOPs Interview Questions and Answers
Ques 11. What is method overloading?
Method overloading is the ability to define multiple methods in the same class with the same name but different parameters.
Example:
class Calculator {
public function add($a, $b) {
return $a + $b;
} public function add($a, $b, $c) {
return $a + $b + $c;
}
}
Ques 12. How is method overriding achieved in PHP?
Method overriding occurs when a child class provides a specific implementation for a method that is already defined in its parent class.
Example:
class Animal {
public function makeSound() {
echo 'Generic Animal Sound';
}
}
class Dog extends Animal {
public function makeSound() {
echo 'Bark';
}
}
Ques 13. What is an interface in PHP?
An interface is a collection of abstract methods. Classes that implement an interface must provide concrete implementations for all its methods.
Example:
interface Logger {
public function logMessage($message);
}
class FileLogger implements Logger {
public function logMessage($message) { // Implementation of logMessage method }
}
Ques 14. What is the 'final' keyword in PHP?
The 'final' keyword is used to prevent a class or method from being extended or overridden by other classes.
Example:
final class FinalClass {
/* class definition */
}
final function finalMethod() {
/* method definition */
}
Ques 15. Explain the concept of abstract classes.
Abstract classes cannot be instantiated and may contain abstract methods, which are methods without a body. Subclasses must provide implementations for all abstract methods.
Example:
abstract class Shape {
abstract public function calculateArea();
}
class Circle extends Shape {
public function calculateArea()
{
// Implementation for Circle's area calculation
}
}
Most helpful rated by users: