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。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 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
- Arrays & Collections
- Type Safety
- Error Handling
- String Handling
- OOP & Modern PHP
- Functions & Closures
- 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)?
它指确保变量和函数使用正确的数据类型(如数字或文本)。这有助于防止程序出现意外错误。
为什么要避免使用“@”来屏蔽错误?
“@”符号会隐藏本该修复的问题。更好的做法是让错误显示出来并妥善处理,这样你才能了解发生了什么,并修复代码。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5895
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。