PHP 面向对象
PHP 从 5.0 起支持完整的面向对象编程,8.x 系列持续增强 OOP 能力。本页覆盖类、继承、接口、Trait、构造器提升等核心概念。
类与对象
class User
{
// PHP 8.1+: readonly 属性,初始化后不可修改
public readonly string $name;
// PHP 8.0+: 构造器属性提升(Constructor Property Promotion)
public function __construct(
string $name,
public int $age = 0,
protected string $role = 'user',
) {
$this->name = $name;
}
public function greet(): string
{
return "Hi, I'm {$this->name}";
}
}
$user = new User(name: "Alice", age: 25); // Named Arguments (8.0+)
echo $user->greet();
构造器属性提升(PHP 8.0)
将属性声明、类型提示和构造函数赋值合并为一处:
// 传统写法
class Point {
public float $x;
public float $y;
public function __construct(float $x, float $y) {
$this->x = $x;
$this->y = $y;
}
}
// PHP 8.0+ 提升写法
class Point {
public function __construct(
public float $x,
public float $y,
) {}
}
可见性
| 修饰符 | 类内 | 子类 | 外部 |
|---|---|---|---|
public | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ❌ |
private | ✅ | ❌ | ❌ |
PHP 8.4 引入了非对称可见性(Asymmetric Visibility),允许 get 和 set 使用不同修饰符:
class Settings {
// 外部可读,但只能在类内修改
public protected(set) string $theme;
}
继承
class Animal {
public function __construct(public string $name) {}
public function speak(): string {
return "...";
}
}
class Dog extends Animal {
// PHP 8.3+: #[\Override] 检查父类方法是否存在
#[\Override]
public function speak(): string {
return "Woof!";
}
}
$dog = new Dog("Rex");
echo $dog->speak(); // Woof!
接口与抽象类
// 接口:定义契约
interface Loggable {
public function toLog(): string;
}
// 抽象类:部分实现
abstract class Model {
abstract public function save(): bool;
public function validate(): bool {
return true;
}
}
// 一个类可实现多个接口
class User extends Model implements Loggable {
public function save(): bool { return true; }
public function toLog(): string { return "User saved"; }
}
Trait
Trait 解决 PHP 单继承的代码复用问题,可看作"水平混入":
trait Timestampable {
public datetime $createdAt;
public function setTimestamp(): void {
$this->createdAt = new datetime();
}
}
class Post {
use Timestampable;
public function __construct() {
$this->setTimestamp();
}
}
枚举(PHP 8.1+)
// 单元枚举
enum Suit {
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
// Backed 枚举(有 string/int 值)
enum Status: string {
case Pending = 'pending';
case Active = 'active';
case Closed = 'closed';
}
// 可定义方法
enum Status: string {
case Pending = 'pending';
case Active = 'active';
public function label(): string {
return match($this) {
self::Pending => '待处理',
self::Active => '活跃',
};
}
}
// 使用
$status = Status::from('active'); // Status::Active
echo $status->label(); // 活跃
Property Hooks(PHP 8.4+)
class Money {
public function __construct(
private int $cents,
) {}
public int $dollars {
get => $this->cents / 100;
set => $this->cents = $value * 100;
}
}
$m = new Money(550);
echo $m->dollars; // 5 (读取走 get hook)
$m->dollars = 10; // 写入走 set hook,cents 变为 1000
静态方法与属性
class Counter {
private static int $count = 0;
public static function create(): static {
self::$count++;
return new static();
}
public static function total(): int {
return self::$count;
}
}
$a = Counter::create();
$b = Counter::create();
echo Counter::total(); // 2
下一步
- PHP 8.x 新特性 — 更多语言层面的变化
- PHP 安全实践 — 密码哈希、注入防护
- PHP 语法与 HTTP — 请求处理、Session、Cookie