What are the advanced features of object-oriented PHP? Implementation and application of inheritance, polymorphism, and interfaces?
考察点:面向对象高级特性。
答案:
PHP面向对象编程提供了继承、多态、接口、抽象类、特性(Traits)等高级特性,这些特性支持更灵活的代码设计和更好的代码复用。
继承机制:
-
基本继承和方法重写:
<?php
class Vehicle {
protected $brand;
protected $speed = 0;
public function __construct($brand) {
$this->brand = $brand;
}
public function start() {
echo "{$this->brand} 启动了<br>";
}
public function accelerate($increment) {
$this->speed += $increment;
echo "当前速度: {$this->speed} km/h<br>";
}
}
class Car extends Vehicle {
private $doors;
public function __construct($brand, $doors) {
parent::__construct($brand);
$this->doors = $doors;
}
public function start() {
parent::start();
echo "汽车发动机启动,{$this->doors}门轿车<br>";
}
public function openTrunk() {
echo "打开后备箱<br>";
}
}
$car = new Car("丰田", 4);
$car->start();
$car->accelerate(50);
?>
-
抽象类和抽象方法:
<?php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
abstract public function calculateArea();
abstract public function draw();
}
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
public function draw() {
echo "绘制{$this->color}的矩形,面积:" . $this->calculateArea() . "<br>";
}
}
$rect = new Rectangle("红色", 10, 5);
$rect->draw();
?>
接口和多态:
-
接口定义和实现:
<?php
interface PaymentInterface {
public function processPayment($amount);
public function refund($transactionId, $amount);
}
interface LoggerInterface {
public function log($message);
}
class AlipayPayment implements PaymentInterface, LoggerInterface {
private $apiKey;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function processPayment($amount) {
$this->log("处理支付宝支付:{$amount}元");
return "支付宝支付成功:{$amount}元";
}
public function refund($transactionId, $amount) {
$this->log("处理支付宝退款:{$transactionId}, {$amount}元");
return "退款成功";
}
public function log($message) {
echo "[" . date('Y-m-d H:i:s') . "] {$message}<br>";
}
}
class WechatPayment implements PaymentInterface, LoggerInterface {
public function processPayment($amount) {
$this->log("处理微信支付:{$amount}元");
return "微信支付成功:{$amount}元";
}
public function refund($transactionId, $amount) {
$this->log("处理微信退款:{$transactionId}, {$amount}元");
return "退款成功";
}
public function log($message) {
echo "[WeChat] {$message}<br>";
}
}
?>
-
多态的应用:
<?php
class PaymentProcessor {
public function processOrder(PaymentInterface $payment, $amount) {
$result = $payment->processPayment($amount);
echo "订单处理结果:{$result}<br>";
return $result;
}
public function handleRefund(PaymentInterface $payment, $transactionId, $amount) {
return $payment->refund($transactionId, $amount);
}
}
$processor = new PaymentProcessor();
$alipay = new AlipayPayment('alipay_key_123');
$wechat = new WechatPayment();
$processor->processOrder($alipay, 100);
$processor->processOrder($wechat, 200);
?>
特性(Traits):
- Traits的定义和使用:
<?php
trait TimestampTrait {
private $createdAt;
private $updatedAt;
public function setCreatedAt() {
$this->createdAt = date('Y-m-d H:i:s');
}
public function setUpdatedAt() {
$this->updatedAt = date('Y-m-d H:i:s');
}
public function getCreatedAt() {
return $this->createdAt;
}
public function getUpdatedAt() {
return $this->updatedAt;
}
}
trait ValidationTrait {
public function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public function validateRequired($value) {
return !empty(trim($value));
}
}
class User {
use TimestampTrait, ValidationTrait;
private $name;
private $email;
public function __construct($name, $email) {
if (!$this->validateRequired($name)) {
throw new Exception("姓名不能为空");
}
if (!$this->validateEmail($email)) {
throw new Exception("邮箱格式无效");
}
$this->name = $name;
$this->email = $email;
$this->setCreatedAt();
}
public function updateEmail($email) {
if ($this->validateEmail($email)) {
$this->email = $email;
$this->setUpdatedAt();
}
}
}
$user = new User("张三", "[email protected]");
echo "用户创建时间:" . $user->getCreatedAt();
?>
高级特性综合应用:
<?php
interface ProductInterface {
public function getName();
public function getPrice();
public function calculateDiscount();
}
abstract class BaseProduct implements ProductInterface {
protected $name;
protected $price;
protected $category;
public function __construct($name, $price, $category) {
$this->name = $name;
$this->price = $price;
$this->category = $category;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
public function getDisplayInfo() {
return sprintf(
"%s - ¥%.2f (%s) - 折扣后:¥%.2f",
$this->getName(),
$this->getPrice(),
$this->category,
$this->calculateDiscount()
);
}
abstract public function calculateDiscount();
}
trait InventoryTrait {
private $stock = 0;
public function setStock($quantity) {
$this->stock = $quantity;
}
public function getStock() {
return $this->stock;
}
public function isInStock() {
return $this->stock > 0;
}
}
class ElectronicsProduct extends BaseProduct {
use InventoryTrait;
private $warranty;
public function __construct($name, $price, $warranty) {
parent::__construct($name, $price, '电子产品');
$this->warranty = $warranty;
}
public function calculateDiscount() {
return $this->price * 0.95;
}
public function getWarranty() {
return $this->warranty;
}
}
class ClothingProduct extends BaseProduct {
use InventoryTrait;
private $size;
public function __construct($name, $price, $size) {
parent::__construct($name, $price, '服装');
$this->size = $size;
}
public function calculateDiscount() {
return $this->price * 0.8;
}
}
$products = [
new ElectronicsProduct("iPhone 15", 6999, "1年保修"),
new ClothingProduct("运动T恤", 199, "L")
];
foreach ($products as $product) {
echo $product->getDisplayInfo() . "<br>";
}
?>
高级特性的优势:
- 代码复用:通过继承和Traits减少重复代码
- 灵活设计:接口和抽象类提供灵活的架构设计
- 多态性:同一接口的不同实现,提高代码的可扩展性
- 职责分离:将通用功能提取为Traits,实现更好的代码组织