php

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PHP Development

PHP开发

Write modern, performant PHP code.
编写现代化、高性能的PHP代码。

When to use

适用场景

  • Writing PHP code
  • PHP 8+ features
  • Performance optimization
  • Laravel/Symfony development
  • 编写PHP代码
  • PHP 8+特性使用
  • 性能优化
  • Laravel/Symfony开发

Modern PHP patterns

现代化PHP模式

Type system (PHP 8+)

类型系统(PHP 8+)

php
// Union types
function process(int|string $id): array|false {
    // ...
}

// Constructor property promotion
class User {
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        private ?int $age = null,
    ) {}
}

// Enums
enum Status: string {
    case Pending = 'pending';
    case Active = 'active';
    case Completed = 'completed';
}

// Match expression
$result = match($status) {
    Status::Pending => 'Waiting',
    Status::Active => 'In Progress',
    Status::Completed => 'Done',
};
php
// Union types
function process(int|string $id): array|false {
    // ...
}

// Constructor property promotion
class User {
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        private ?int $age = null,
    ) {}
}

// Enums
enum Status: string {
    case Pending = 'pending';
    case Active = 'active';
    case Completed = 'completed';
}

// Match expression
$result = match($status) {
    Status::Pending => 'Waiting',
    Status::Active => 'In Progress',
    Status::Completed => 'Done',
};

Generators

生成器

php
// Memory-efficient iteration
function readLargeFile(string $path): Generator {
    $handle = fopen($path, 'r');
    while (($line = fgets($handle)) !== false) {
        yield trim($line);
    }
    fclose($handle);
}

// Usage
foreach (readLargeFile('huge.csv') as $line) {
    processLine($line);
}

// Generator with keys
function parseCSV(string $path): Generator {
    $handle = fopen($path, 'r');
    $headers = fgetcsv($handle);
    while (($row = fgetcsv($handle)) !== false) {
        yield array_combine($headers, $row);
    }
    fclose($handle);
}
php
// Memory-efficient iteration
function readLargeFile(string $path): Generator {
    $handle = fopen($path, 'r');
    while (($line = fgets($handle)) !== false) {
        yield trim($line);
    }
    fclose($handle);
}

// Usage
foreach (readLargeFile('huge.csv') as $line) {
    processLine($line);
}

// Generator with keys
function parseCSV(string $path): Generator {
    $handle = fopen($path, 'r');
    $headers = fgetcsv($handle);
    while (($row = fgetcsv($handle)) !== false) {
        yield array_combine($headers, $row);
    }
    fclose($handle);
}

SPL data structures

SPL数据结构

php
// Priority queue
$queue = new SplPriorityQueue();
$queue->insert('low', 1);
$queue->insert('high', 10);
$queue->insert('medium', 5);

while (!$queue->isEmpty()) {
    echo $queue->extract(); // high, medium, low
}

// Fixed array (memory efficient)
$arr = new SplFixedArray(1000);
$arr[0] = 'value';
php
// Priority queue
$queue = new SplPriorityQueue();
$queue->insert('low', 1);
$queue->insert('high', 10);
$queue->insert('medium', 5);

while (!$queue->isEmpty()) {
    echo $queue->extract(); // high, medium, low
}

// Fixed array (memory efficient)
$arr = new SplFixedArray(1000);
$arr[0] = 'value';

Error handling

错误处理

php
// Custom exceptions
class ValidationException extends Exception {
    public function __construct(
        public readonly string $field,
        string $message,
    ) {
        parent::__construct($message);
    }
}

// Try-catch with multiple types
try {
    process($data);
} catch (ValidationException $e) {
    log("Validation failed: {$e->field}");
} catch (RuntimeException $e) {
    log("Runtime error: {$e->getMessage()}");
} finally {
    cleanup();
}
php
// Custom exceptions
class ValidationException extends Exception {
    public function __construct(
        public readonly string $field,
        string $message,
    ) {
        parent::__construct($message);
    }
}

// Try-catch with multiple types
try {
    process($data);
} catch (ValidationException $e) {
    log("Validation failed: {$e->field}");
} catch (RuntimeException $e) {
    log("Runtime error: {$e->getMessage()}");
} finally {
    cleanup();
}

Attributes (PHP 8)

注解(PHP 8)

php
#[Attribute(Attribute::TARGET_METHOD)]
class Route {
    public function __construct(
        public string $path,
        public string $method = 'GET',
    ) {}
}

class Controller {
    #[Route('/users', 'GET')]
    public function listUsers(): array {
        // ...
    }
}
php
#[Attribute(Attribute::TARGET_METHOD)]
class Route {
    public function __construct(
        public string $path,
        public string $method = 'GET',
    ) {}
}

class Controller {
    #[Route('/users', 'GET')]
    public function listUsers(): array {
        // ...
    }
}

Best practices

最佳实践

  • Use strict types:
    declare(strict_types=1);
  • Follow PSR-12 coding standard
  • Use Composer for autoloading
  • Prefer built-in functions over custom
  • Use generators for large datasets
  • 使用严格类型:
    declare(strict_types=1);
  • 遵循PSR-12编码标准
  • 使用Composer实现自动加载
  • 优先使用内置函数而非自定义函数
  • 对大型数据集使用生成器

Examples

示例

Input: "Optimize this PHP code" Action: Profile with Xdebug, use generators, leverage SPL structures
Input: "Modernize to PHP 8" Action: Add type hints, use match/enums, constructor promotion
输入: "优化这段PHP代码" 操作: 使用Xdebug进行性能分析,使用生成器,利用SPL数据结构
输入: "升级到PHP 8现代化改造" 操作: 添加类型提示,使用match/枚举,使用构造函数属性提升