__clone 메서드

__clone 메서드는 clone 연산자를 사용할 때 자동으로 호출됩니다. 이 메서드를 사용하면 객체 복사의 자체 로직을 정의할 수 있습니다. 기본적으로 PHP는 객체의 모든 속성을 얕은 복사를 수행합니다. __clone 메서드는 깊은 복사를 구현해야 하거나 복제 시 동작을 변경해야 할 때 유용합니다.

문법

phppublic function __clone(): void

예제

객체의 기본 복제를 구현해 봅시다:

php<?php
  class User {
    public $name;
    
    public function __construct($name) {
      $this->name = $name;
    }
    
    public function __clone() {
      echo '객체가 복제되었습니다';
    }
  }
  
  $user1 = new User('John');
  $user2 = clone $user1;
?>

코드 실행 결과:

php'객체가 복제되었습니다'

예제

중첩된 객체를 가진 객체의 깊은 복사를 구현해 봅시다:

php<?php
  class Address {
    public $city;
    
    public function __construct($city) {
      $this->city = $city;
    }
  }
  
  class User {
    public $name;
    public $address;
    
    public function __construct($name, $city) {
      $this->name = $name;
      $this->address = new Address($city);
    }
    
    public function __clone() {
      $this->address = clone $this->address;
    }
  }
  
  $user1 = new User('John', 'New York');
  $user2 = clone $user1;
  $user2->address->city = 'Boston';
  
  echo $user1->address->city;
?>

코드 실행 결과:

php'New York'

예제

복제 시 고유 식별자를 추가해 봅시다:

php<?php
  class Product {
    public $id;
    public $name;
    
    public function __construct($name) {
      $this->id = uniqid();
      $this->name = $name;
    }
    
    public function __clone() {
      $this->id = uniqid();
    }
  }
  
  $product1 = new Product('Laptop');
  $product2 = clone $product1;
  
  echo $product1->id . ' ' . $product2->id;
?>

코드 실행 결과 (예시):

php'5f1a2b3c 5f1a2b3d'

함께 보기