PHP/Class/Destructors — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 10:37, 26 мая 2010

Accessing instance-specific data within a destructor

 
class Database {
    function __destruct() {
         db_close($this->handle); 
    }
}



Class destructors

<?php
   class Book
   {
      private $title;
      private $isbn;
      private $copies;
      function __construct($isbn)
      {
         echo "<p>Book class instance created.</p>";
      }
      function __destruct()
      {
         echo "<p>Book class instance destroyed.</p>";
      }
   }
   $book = new Book("1111");
?>



Class with destructors

 
<?php
    class Book
    {
        private $title;
        private $isbn;
        private $copies;
        function __construct($isbn)
        {
            echo "<p>Book class instance created.</p>";
        }
        function __destruct()
        {
            echo "<p>Book class instance destroyed.</p>";
        }  
    }
    $book = new Book("111111111111");
?>



Cleaning Up with the __destruct Method (PHP 5 Only)

 
<?php
class ItemUpdater {
  public function update( Item $item ) {
    print "updating.. ";
    print $item->name;
  }
}
class Item {
  public $name = "item";
  private $updater;
  public function setUpdater( ItemUpdater $update ) {
    $this->updater=$update;
  }
  function __destruct() {
    if ( ! empty( $this->updater )) {
      $this->updater->update( $this );
    }
  }
}
$item = new Item();
$item->setUpdater( new ItemUpdater() ) ;
unset( $item );
?>



Declaring and Using Object Constructors and Destructors

 
<?php
class cd {
    public $artist;
    public $title;
    protected $tracks;
    private $disk_id;
    public function __construct() {
        $this->disk_id = sha1("cd" . time() . rand());
    }
    public function get_disk_id() {
        return $this->disk_id;
    }
}
$mydisk = new cd();
echo $mydisk->get_disk_id();
?>



Defining an object destructor

 
class car {
    function __destruct() {
    }
}



destuctor in action

<?php
class Person {
    protected $name;    
    private $age;    
    private $id;    
    function __construct( $name, $age ) {
        $this->name = $name;
        $this->age  = $age;
    }
    function setId( $id ) {
        $this->id = $id;
    }
    
    function __destruct() {
        if ( ! empty( $this->id ) ) {
            print "saving person\n";
        }
    }
}
$person = new Person( "Joe", 31 );
$person->setId( 111 );
unset( $person );
?>