面向对象可以把数据和行为封装在一起,适合构建中大型应用。现代 PHP 项目通常配合 Composer 使用命名空间。

本节要点

  • class 定义类,new 创建对象。
  • public、protected、private 控制成员访问权限。
  • 接口定义能力契约,类通过 implements 实现。

代码示例

<?php
namespace App;

interface Notifier
{
    public function send(string $message): void;
}

class EmailNotifier implements Notifier
{
    public function __construct(private string $to) {}

    public function send(string $message): void
    {
        echo "发送邮件到 {$this->to}:{$message}";
    }
}

$notifier = new EmailNotifier("[email protected]");
$notifier->send("欢迎注册");