面向对象编程:从类到接口的完整体系
PHP的OOP模型在7.x版本后已高度成熟,支持:
- 类与对象:构造函数(__construct)、析构函数(__destruct)、属性/方法可见性(public/protected/private)、final关键字(禁止继承/重写)。
- 抽象类与接口:抽象类(abstract class)可含具体方法;接口(interface)仅定义方法签名,支持多实现。
- trait:解决单继承局限,复用代码块(如Loggable trait可为任意类添加日志功能)。
- 魔术方法:__call()(调用不可见方法)、__get/__set(属性访问拦截)、__toString()(对象转字符串)、__invoke()(对象当函数调用)。
示例:使用trait实现多继承式日志记录
trait Logger {
private $logFile = 'app.log';
public function log($level, $message) {
$context = date('Y-m-d H:i:s') . " [{$level}] {$message}\n";
file_put_contents($this->logFile, $context, FILE_APPEND);
}
}
class UserService {
use Logger;
public function createUser($data) {
$this->log('INFO', '创建用户: ' . $data['email']);
// 业务逻辑...
}
}
$service = new UserService();
$service->log('DEBUG', '调试信息'); // 直接调用trait方法
关键点:trait中属性不能与类中属性重复;多个trait冲突时用insteadof指定优先级,as设置别名。
类型系统演进:从松散到严格
PHP的类型系统经历了显著进化:
- PHP 5:引入类、接口类型提示(type hinting),但标量类型(int/string)需通过函数参数默认值规避。
- PHP 7.0:新增标量类型声明(declare(strict_types=1)开启严格模式),返回类型声明(: string)。
- PHP 7.1:支持void返回类型、可空类型(?int)。
- PHP 7.4:添加属性类型声明(public int $id)。
- PHP 8.0:联合类型(int|string)、属性类型增强(支持readonly)、构造函数属性提升(public int $id)。
示例:PHP 8.0属性类型声明
class User {
public function __construct(
public int $id,
public string $name,
public ?string $email = null,
public readonly \DateTime $createdAt
) {}
}
$user = new User(
id: 1,
name: '张三',
email: 'zhangsan@example.com',
createdAt: new \DateTime()
);
echo $user->id; // 1
// $user->id = 2; // 报错:readonly属性不可修改
注意事项:严格模式(declare(strict_types=1))必须放在文件顶部,影响当前文件所有函数调用;联合类型中null必须用?前缀,不可与其他类型并列(如?int|string非法)。
设计模式实践:企业级开发的通用方案
PHP开发中高频使用的5大模式:
- 工厂模式:解耦对象创建,如DatabaseFactory根据配置返回PDO实例。
- 单例模式:确保类仅有一个实例(如配置管理器Config::getInstance())。
- 观察者模式:事件驱动架构基础,如SplObserver/SplSubject实现用户注册后触发邮件发送。
- 策略模式:替换if-else分支,如PaymentStrategy接口下实现AlipayStrategy/WechatPayStrategy。
- 依赖注入:通过构造函数/Setter注入依赖,提升可测试性(如Controller依赖UserService)。
示例:策略模式实现支付系统
interface PaymentStrategy {
public function pay($amount);
}
class AlipayStrategy implements PaymentStrategy {
public function pay($amount) {
echo "支付宝支付{$amount}元\n";
}
}
class WechatPayStrategy implements PaymentStrategy {
public function pay($amount) {
echo "微信支付{$amount}元\n";
}
}
class PaymentContext {
private $strategy;
public function setStrategy(PaymentStrategy $strategy) {
$this->strategy = $strategy;
}
public function checkout($amount) {
$this->strategy->pay($amount);
}
}
// 客户端调用
$payment = new PaymentContext();
$payment->setStrategy(new AlipayStrategy());
$payment->checkout(99.00); // 支付宝支付99元