PHpullh
언어 비교/Variable

LANGUAGE COMPARISON

Variable를 언어별로 비교하기

같은 개념을 실제 예제로 나란히 확인하고, 각 언어의 개별 설명으로 이어갈 수 있습니다.

Python

Context Variables & 의존성 주입

의존성 주입 패턴과 contextvars 로 스레드/코루틴 안전한 컨텍스트를 관리합니다.

from contextvars import ContextVar
from typing import Optional
import asyncio

# ContextVar — 코루틴/스레드마다 독립적인 값
current_user: ContextVar[Optional[str]] = ContextVar(
    "current_user", default=None
)
request_id: ContextVar[str] = ContextVar("request_id")

async def handle_request(user: str, req_id: str):
    current_user.set(user)
    request_id.set(req_id)
    await process()

async def process():
    user = current_user.get()
    rid  = request_id.get()
    print(f"[{rid}] {user} 처리 중")
    await asyncio.sleep(0.01)

# 의존성 주입 — 간단한 컨테이너
class Container:
    _services = {}

    @classmethod
    def register(cls, name: str, factory):
        cls._services[name] = factory

    @classmethod
    def resolve(cls, name: str):
        return cls._services[name]()

# 등록
Container.register("db", lambda: {"connected": True})
Container.register("cache", lambda: {})

# 사용
db    = Container.resolve("db")
cache = Container.resolve("cache")

async def main():
    await asyncio.gather(
        handle_request("Alice", "req-001"),
        handle_request("Bob",   "req-002"),
    )

asyncio.run(main())

Go

sync.Cond

sync.Cond 로 조건 변수를 구현합니다. 특정 조건이 충족될 때까지 고루틴을 대기시킵니다.

package main

import (
	"fmt"
	"sync"
	"time"
)

type Queue struct {
	items []int
	cond  *sync.Cond
}

func NewQueue() *Queue {
	return &Queue{cond: sync.NewCond(&sync.Mutex{})}
}

func (q *Queue) Enqueue(item int) {
	q.cond.L.Lock()
	defer q.cond.L.Unlock()
	q.items = append(q.items, item)
	q.cond.Signal() // 대기 중인 하나를 깨움
}

func (q *Queue) Dequeue() int {
	q.cond.L.Lock()
	defer q.cond.L.Unlock()
	for len(q.items) == 0 {
		q.cond.Wait() // 조건 대기 (잠금 해제 → 대기 → 잠금 획득)
	}
	item := q.items[0]
	q.items = q.items[1:]
	return item
}

func main() {
	q := NewQueue()

	// 소비자
	go func() {
		for i := 0; i < 5; i++ {
			val := q.Dequeue()
			fmt.Println("소비:", val)
		}
	}()

	// 생산자
	for i := 1; i <= 5; i++ {
		time.Sleep(200 * time.Millisecond)
		q.Enqueue(i)
		fmt.Println("생산:", i)
	}
	time.Sleep(100 * time.Millisecond)
}

Java

var & 타입 추론 (Java 10+)

Java 10에 추가된 지역 변수 타입 추론 var 로 코드를 간결하게 작성합니다.

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class VarExample {
    public static void main(String[] args) {
        // var — 지역 변수에서만 사용
        var name = "Java";             // String 추론
        var version = 21;              // int 추론
        var pi = 3.14159;              // double 추론
        var active = true;             // boolean 추론

        // 컬렉션에서 특히 유용
        var list = new ArrayList<String>();
        list.add("Hello");
        list.add("World");

        // for-each에서도 사용 가능
        for (var item : list) {
            System.out.println(item);
        }

        // Map.entry 순회 시 매우 편리
        var map = Map.of("a", 1, "b", 2, "c", 3);
        for (var entry : map.entrySet()) {
            System.out.printf("%s = %d%n",
                entry.getKey(), entry.getValue());
        }

        // 컴파일러가 실제 타입을 추론 — 런타임에 타입 보존
        System.out.println(((Object)name).getClass().getName());
    }
}

PHP

변수와 기본 타입

문자열, 정수, 불리언 등 PHP의 기본 타입을 확인하는 예제입니다.

<?php
$name = 'PHP';
$year = 2026;
$isStable = true;

var_dump($name, $year, $isStable);