PHpullh
학습 라이브러리/PHP/객체 복제와 __clone

PHP · 객체지향

객체 복제와 __clone

기본 빌더를 복제해 일부 조건만 다르게 조합할 때 쓰는 clone 예제입니다.

객체지향고급clone__clonebuilder

핵심 설명

기본 빌더를 복제해 일부 조건만 다르게 조합할 때 쓰는 clone 예제입니다.

PHP code

<?php
class QueryBuilder {
    public function __construct(public array $wheres = []) {}

    public function __clone(): void {
        $this->wheres = array_values($this->wheres);
    }
}

$base = new QueryBuilder(['active = 1']);
$copy = clone $base;
$copy->wheres[] = 'role = "admin"';

print_r([$base->wheres, $copy->wheres]);

학습 팁

클래스 예제는 생성자, 가시성, 협력 객체의 책임을 함께 보면 실무 감각이 빨리 붙습니다.

주의할 점

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.

자주 묻는 질문

객체 복제와 __clone란 무엇인가요?

기본 빌더를 복제해 일부 조건만 다르게 조합할 때 쓰는 clone 예제입니다.

객체 복제와 __clone 학습 시 주의할 점은 무엇인가요?

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.