__clone metodi

__clone metodi clone operator ulanylanda awtomatik çagyrylýar. Ol obýektiň öz göçürmek logikasyny kesgitlemäge mümkinçilik berýär. Öňünden PHP obýektiň ähli aýratynlyklarynyň ýokarky göçürmesini ýerine ýetirýär. __clone metodi çuň göçürmek amala aşyrmaly ýa-da klonlanylanda hereketini üýtgetmeli bolan ýerlerde peýdaly.

Sintaksis

phppublic function __clone(): void

Mysal

Obýektiň esas klonlamasyny amala aşyralyň:

php<?php
  class User {
    public $name;
    
    public function __construct($name) {
      $this->name = $name;
    }
    
    public function __clone() {
      echo 'Obýekt klonlandy';
    }
  }
  
  $user1 = new User('John');
  $user2 = clone $user1;
?>

Kodyň netijesi:

php'Obýekt klonlandy'

Mysal

Içine goýlan obýektleri bolan obýektiň çuň göçürmesini amala aşyralyň:

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;
?>

Kodyň netijesi:

php'New York'

Mysal

Klonlanylanda yzygiderli identifikator goşalyň:

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;
?>

Kodyň netijesi (mysal):

php'5f1a2b3c 5f1a2b3d'

Şeýle-de görüň