跳到正文
Skillpedia
通用编程48k · #5895

php

它能做什么

这份指南教你如何更高效、更现代地编写 PHP 代码。它展示了更好的数据组织方式、错误处理方式,以及如何使用较新的语言特性,让代码更清晰、更安全。

适用场景

  • ✓当你开始学习 PHP 编程时。
  • ✓当你需要审查或改进现有的 PHP 代码时。
  • ✓当你想使用最新、最高效的 PHP 版本时。

技能链接

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/php/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/php/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“如何在处理数据时让我的 PHP 代码更安全?”

每周 5 个新技能,1 分钟读完。

工作原理

指南会将“不好”的代码示例与“好”的示例进行对比,以说明最佳实践。它重点介绍如何使用特定的语言函数和现代特性来简化常见任务。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

PHP: Idiomatic Efficiency Reference

When to Use

  • Use this skill when the task matches this description: Language-specific super-code guidelines for php.

Table of Contents

  1. Arrays & Collections
  2. Type Safety
  3. Error Handling
  4. String Handling
  5. OOP & Modern PHP
  6. Functions & Closures
  7. Anti-patterns specific to PHP

1. Arrays & Collections {#arrays}

// ❌ Manual accumulation
$result = [];
foreach ($items as $item) {
    if ($item->isActive()) {
        $result[] = strtoupper($item->getName());
    }
}

// ✅
$result = array_map(
    fn($i) => strtoupper($i->getName()),
    array_filter($items, fn($i) => $i->isActive())
);
// ❌ Manual key-value grouping
$grouped = [];
foreach ($items as $item) {
    $grouped[$item->getCategory()][] = $item;
}

// ✅ (PHP 8.1+) — or use the loop above; PHP lacks a built-in groupBy
// The foreach is actually idiomatic PHP for grouping. No need to force array_* here.
// ❌ Checking isset then accessing
if (isset($data['key'])) {
    $value = $data['key'];
} else {
    $value = 'default';
}

// ✅
$value = $data['key'] ?? 'default';
// ❌ array_push for single element
array_push($items, $newItem);

// ✅
$items[] = $newItem;

Use array_map/array_filter for transforms. The foreach loop is fine when array functions would be less readable.


2. Type Safety {#types}

// ❌ No type declarations
function process($items) {
    return $items;
}

// ✅ (PHP 8.0+)
function process(array $items): array {
    return $items;
}
// ❌ Union type for nullable
function find(string $key): string|null { ... }

// ✅
function find(string $key): ?string { ... }
// ❌ Loose comparison
if ($value == '0') { ... } // true for 0, '', false, null

// ✅
if ($value === '0') { ... }
// ❌ Type checking with gettype()
if (gettype($x) === 'integer') { ... }

// ✅
if (is_int($x)) { ... }
// or with union types, avoid checks entirely

Enable declare(strict_types=1) at the top of every file.


3. Error Handling {#errors}

// ❌ Suppressing errors with @
$data = @file_get_contents($path);

// ✅
$data = file_get_contents($path);
if ($data === false) {
    throw new RuntimeException("Failed to read: $path");
}
// ❌ Catching \Exception and swallowing
try { process(); }
catch (\Exception $e) { /* silence */ }

// ✅
try {
    process();
} catch (SpecificException $e) {
    $this->logger->error($e->getMessage(), ['exception' => $e]);
    throw new AppException('Processing failed', previous: $e);
}
// ❌ Returning mixed types for error indication
function divide(int $a, int $b): int|false {
    if ($b === 0) return false;
    return intdiv($a, $b);
}

// ✅ — throw exception for exceptional cases
function divide(int $a, int $b): int {
    if ($b === 0) throw new \DivisionByZeroError();
    return intdiv($a, $b);
}

4. String Handling {#strings}

// ❌ Concatenation for variable interpolation
$msg = 'Hello, ' . $name . '! You have ' . $count . ' messages.';

// ✅
$msg = "Hello, {$name}! You have {$count} messages.";
// ❌ Manual string contains check
if (strpos($haystack, $needle) !== false) { ... }

// ✅ (PHP 8.0+)
if (str_contains($haystack, $needle)) { ... }
// ❌ substr for prefix/suffix check
if (substr($str, 0, 4) === 'http') { ... }
if (substr($str, -4) === '.php') { ... }

// ✅ (PHP 8.0+)
if (str_starts_with($str, 'http')) { ... }
if (str_ends_with($str, '.php')) { ... }

5. OOP & Modern PHP {#oop}

// ❌ Manual constructor property assignment
class User {
    private string $name;
    private int $age;
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

// ✅ (PHP 8.0+)
class User {
    public function __construct(
        private readonly string $name,
        private readonly int $age,
    ) {}
}
// ❌ Constants as class properties
class Status {
    const ACTIVE = 'active';
    const INACTIVE = 'inactive';
}

// ✅ (PHP 8.1+)
enum Status: string {
    case Active = 'active';
    case Inactive = 'inactive';
}
// ❌ instanceof chains
if ($shape instanceof Circle) { ... }
elseif ($shape instanceof Rectangle) { ... }

// ✅ (PHP 8.0+)
$area = match(true) {
    $shape instanceof Circle => $shape->radius ** 2 * M_PI,

…
常见问题

什么是“Arrays & Collections”?

这是在 PHP 中组织和处理数据列表的方法。指南展示了如何使用内置函数代替手写循环,让代码更短、更易读。

什么是“类型安全”(Type Safety)?

它指确保变量和函数使用正确的数据类型(如数字或文本)。这有助于防止程序出现意外错误。

为什么要避免使用“@”来屏蔽错误?

“@”符号会隐藏本该修复的问题。更好的做法是让错误显示出来并妥善处理,这样你才能了解发生了什么,并修复代码。

详情

作者的原始描述

Language-specific super-code guidelines for php.

repo: sickn33/agentic-awesome-skills

热度

GitHub 星标
48k
排名
#5895
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能