آموزش متد جادویی destruct__

  • خانه
  • آموزش متد جادویی destruct__
Image تحقیقات

آموزش متد جادویی destruct__

سلامی دیگر

خب امروز میریم سراغ متد جایی destruct__  در زبان آموزش php. همانطورکه از نام این متد هم میشه حدس زد این متد زمانی فراخوانی می شود که آبجکت کلاسی از بین برود و حذف شود. متد متد جایی destruct__ هیچ آرگمان ورودی ندارد  و اگه بخوایم کاراییش رو بدونیم  بیشتر جنبه ی تمیز کاری داری..مثلا برای بستن اتصال دیتابیس بعد از تمام شد کارمون با کلاس . یا بستن یک فایل بعد از اتمام کار با کلاس خاصی و …

مانند مثال زیر :

<?php
class Device {
    public $name;           // the name of the device
    public $battery;        // holds a Battery object
    public $data = array(); // stores misc. data in an array
    public $connection;     // holds some connection resource

   
    public function  __destruct() {
        // disconnect from the network
        $this->disconnect();
        echo $this->name . ' was destroyed' . PHP_EOL;
    }
   
    
 
    protected function connect() {
        // connect to some external network
        $this->connection = 'resource';
        echo $this->name . ' connected' . PHP_EOL;
    }
 
    protected function disconnect() {
        // safely disconnect from network
        $this->connection = null;
        echo $this->name . ' disconnected' . PHP_EOL;
    }
}
 
class Battery {
    private $charge = 0;
 
    public function setCharge($charge) {
        $charge = (int)$charge;
        if($charge < 0) {
            $charge = 0;
        }
        elseif($charge > 100) {
            $charge = 100;
        }
        $this->charge = $charge;
    }
}

همانند متد سازنده () متدهای مخرب () نیز به صورت اتوماتیک متد سازنده ی پدر را فراخوانی نمیکنن که در صورت نیاز باید به صورت دستی و با وارد کردن عبارت زیر ان کار را انجام داد :

parent::__destruct() ;

مثال :

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
   		parent::__destruct() ;
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();

در قسمت های بعدی با متدهای دیگر آشنا می شویم.