PHP OOPs 面试题与答案
问题 26. What is the purpose of the 'final' keyword when applied to a class method?
When a method is marked as 'final,' it cannot be overridden by subclasses. It provides a way to prevent further modification of a specific method in a class hierarchy.
Example:
class Example {
final public function cannotOverride() { /* method implementation */ }
}
问题 27. Explain the concept of the Observer design pattern.
The Observer pattern defines a one-to-many dependency between objects, where if one object changes its state, all its dependents are notified and updated automatically.
Example:
class Subject {
private $observers = [];
public function addObserver(Observer $observer) {
$this->observers[] = $observer; }
public function notifyObservers() {
foreach ($this->observers as $observer) { $observer->update(); } } }
问题 28. What is the purpose of the 'abstract' keyword in PHP?
The 'abstract' keyword is used to declare an abstract class or method. Abstract classes cannot be instantiated, and abstract methods must be implemented by the subclasses.
Example:
abstract class Shape {
abstract public function calculateArea();
}
问题 29. Explain the concept of late static binding and how it differs from static binding.
Late static binding allows accessing the called class using the 'static' keyword, while static binding refers to the class in which the method is defined. Late static binding is resolved at runtime.
Example:
class ParentClass {
public static function whoAmI() {
echo static::class; } }
class ChildClass extends ParentClass { }
ChildClass::whoAmI(); // Outputs 'ChildClass'
问题 30. What is the purpose of the 'clone' keyword in PHP?
The 'clone' keyword is used to create a copy of an object. It performs a shallow copy by default, but the __clone() method can be implemented to customize the cloning process.
Example:
class MyClass {
public $property;
public function __clone() { // Additional cloning logic if needed } }
$obj1 = new MyClass(); $obj2 = clone $obj1;
用户评价最有帮助的内容:
- What is Object-Oriented Programming (OOP)?
- Explain the four pillars of OOP.
- How does inheritance work in PHP?