Tan Kim

PHP

서버사이드 스크립트 언어. 웹 개발에 특화되어 있으며 WordPress, Laravel 등의 기반.

기본 문법

<?php
 
// 변수 ($로 시작)
$name = "김탄";
$age = 30;
$isActive = true;
 
// 문자열
echo "안녕, $name";          // 변수 보간 (큰따옴표)
echo '안녕, $name';          // 리터럴 (작은따옴표)
echo "나이: " . $age;        // 연결 연산자
 
// 타입 확인
gettype($name);   // string
is_string($name); // true

배열

// 인덱스 배열
$fruits = ["apple", "banana", "cherry"];
$fruits[] = "date";        // 추가
count($fruits);            // 4
 
// 연관 배열 (딕셔너리)
$user = [
    "name" => "김탄",
    "age"  => 30,
];
$user["name"];             // 김탄
array_key_exists("name", $user); // true
 
// 유용한 함수
array_push($arr, $val);
array_pop($arr);
array_merge($a, $b);
array_map(fn($x) => $x * 2, $nums);
array_filter($arr, fn($x) => $x > 0);
array_values($arr);        // 인덱스 재정렬
in_array("apple", $fruits); // true
implode(", ", $fruits);    // "apple, banana, cherry"
explode(",", "a,b,c");     // ["a","b","c"]

제어문

// 조건문
if ($age >= 18) {
    echo "성인";
} elseif ($age >= 13) {
    echo "청소년";
} else {
    echo "어린이";
}
 
// match (PHP 8.0+)
$label = match(true) {
    $age >= 18 => "성인",
    $age >= 13 => "청소년",
    default    => "어린이",
};
 
// 반복문
foreach ($fruits as $fruit) {
    echo $fruit;
}
foreach ($user as $key => $value) {
    echo "$key: $value";
}
for ($i = 0; $i < 10; $i++) {}
while ($condition) {}

함수

function greet(string $name, string $greeting = "안녕"): string {
    return "$greeting, $name!";
}
 
// 가변 인자
function sum(int ...$nums): int {
    return array_sum($nums);
}
 
// 화살표 함수 (PHP 7.4+)
$double = fn($x) => $x * 2;
 
// 클로저
$multiplier = 3;
$triple = function($x) use ($multiplier) {
    return $x * $multiplier;
};

클래스

class Animal {
    public function __construct(
        protected string $name  // 생성자 프로모션 (PHP 8.0+)
    ) {}
 
    public function speak(): string {
        return "";
    }
}
 
class Dog extends Animal {
    public function speak(): string {
        return "{$this->name}: 왈왈";
    }
}
 
// 인터페이스
interface Speakable {
    public function speak(): string;
}
 
// Trait
trait Loggable {
    public function log(string $msg): void {
        echo "[LOG] $msg";
    }
}

예외 처리

try {
    throw new \InvalidArgumentException("잘못된 값");
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage();
} catch (\Exception $e) {
    echo "일반 오류: " . $e->getMessage();
} finally {
    echo "항상 실행";
}

자주 쓰는 내장 함수

// 문자열
strlen($str);
strtolower($str);
strtoupper($str);
trim($str);
str_replace("old", "new", $str);
str_contains($str, "sub");    // PHP 8.0+
substr($str, 0, 5);
sprintf("이름: %s, 나이: %d", $name, $age);
 
// 날짜
date("Y-m-d");
date("Y-m-d H:i:s");
strtotime("2026-01-01");
 
// JSON
json_encode($array);          // 배열 → JSON 문자열
json_decode($json, true);     // JSON 문자열 → 배열
 
// 기타
isset($var);       // 변수 존재 + null 아님
empty($var);       // 비어있음 (0, "", null, [] 등)
var_dump($var);    // 타입 + 값 출력

Null 안전 연산자 (PHP 8.0+)

$city = $user?->getAddress()?->getCity();  // null이면 null 반환
$name = $user ?? "기본값";                  // null 병합
$user ??= "기본값";                         // null이면 대입

메모