首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 編碼規範(十):類聲明格式、方法分隔與空方法簡寫規範

     編輯:PHP 相關知識

類聲明格式

<?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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved