類聲明格式
<?php
declare(strict_types=1);
namespace App\Entity;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
* 用戶實體
*/
#[ORM\Entity]
class User
{
// 屬性...
}
大括號風格
- 類/介面/方法/控制結構:左大括號
{ 與聲明**同行末尾**,前方一空格
- 右大括號
}:獨佔一行,與對應聲明**左對齊**
- 空體:
{} 緊湊書寫,中間無空格換行
<?php
class Sample extends BaseEntity
{
public function __construct(public string $name) {}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function emptyMethod() {}
}
方法之間分隔
- **方法之間空一行** (單個空行)
- 屬性組與第一個方法之間空一行
- 最後一個方法與類右大括號之間**無空行**
<?php
class Service
{
private Repository $repo;
public function __construct(Repository $repo)
{
$this->repo = $repo;
}
public function find(int $id): ?Entity
{
return $this->repo->find($id);
}
public function save(Entity $entity): void
{
$this->repo->save($entity);
}
}
屬性鉤子 (PHP 8.4) 格式
<?php
class User
{
public string $email {
get => $this->email;
set(string $value) {
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email');
}
$this->email = strtolower($value);
}
}
}
Enum 聲明格式 (PHP 8.1+)
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string
{
return match ($this) {
self::Draft => '草稿',
self::Published => '已發布',
self::Archived => '已歸檔',
};
}
}
介面聲明格式
<?php
interface PaymentGatewayInterface
{
public const SUPPORTED_CURRENCIES = ['USD', 'EUR'];
public function charge(float $amount, string $currency): PaymentResult;
public function refund(string $transactionId): RefundResult;
}