PHP OOPs 面试题与答案
问题 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;
}
}
问题 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';
}
}
问题 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 }
}
问题 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 */
}
问题 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
}
}
用户评价最有帮助的内容:
- What is Object-Oriented Programming (OOP)?
- Explain the four pillars of OOP.
- How does inheritance work in PHP?