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에 붙여넣으세요. 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,
…
자주 묻는 질문
'배열과 컬렉션'이란 무엇인가요?
PHP에서 데이터 목록을 정리하고 다루는 방법입니다. 가이드는 직접 반복문을 쓰는 대신 내장 함수를 사용해 코드를 더 짧고 읽기 쉽게 만드는 방법을 보여 줍니다.
'타입 안전성'이란 무엇인가요?
변수와 함수가 올바른 데이터 타입(숫자나 텍스트 등)을 사용하도록 보장하는 것입니다. 프로그램에서 예상치 못한 오류를 막는 데 도움이 됩니다.
오류 억제를 위해 '@'를 피해야 하는 이유는 무엇인가요?
'@' 기호는 해결해야 할 문제를 숨깁니다. 오류가 드러나도록 두고 제대로 처리하는 편이 무슨 일이 일어났는지 이해하고 코드를 고치는 데 더 낫습니다.
상세 정보
인기도
- 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에이전트가 신뢰할 수 있는 자료를 바탕으로 특정 산업의 맥락, 규칙, 사용 패턴, 위험을 정리한 요약을 만들도록 돕습니다.