เมธอด __clone

เมธอด __clone ถูกเรียกอัตโนมัติเมื่อใช้โอเปอเรเตอร์ clone มันช่วยให้กำหนดลอจิกการคัดลอกอ็อบเจ็กต์เองได้ โดยค่าเริ่มต้น PHP ทำการคัดลอกแบบตื้น (shallow copy) คุณสมบัติทั้งหมดของอ็อบเจ็กต์ เมธอด __clone มีประโยชน์ เมื่อต้องการใช้งานการคัดลอกแบบลึก (deep copy) หรือเปลี่ยนพฤติกรรมเมื่อโคลน

ไวยากรณ์

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'

ดูเพิ่มเติม

  • เมธอด __construct,
    ซึ่งเป็นตัวสร้างอ็อบเจ็กต์ (constructor)