PHP/Class/Destructors
Содержание
Accessing instance-specific data within a destructor
<source lang="html4strict">
class Database {
function __destruct() { db_close($this->handle); }
}
</source>
Class destructors
<source lang="html4strict">
<?php
class Book { private $title; private $isbn; private $copies; function __construct($isbn) {echo "
Book class instance created.
";} function __destruct() {echo "
Book class instance destroyed.
";} } $book = new Book("1111");
?>
</source>
Class with destructors
<source lang="html4strict">
<?php
class Book { private $title; private $isbn; private $copies; function __construct($isbn) {echo "
Book class instance created.
";} function __destruct() {echo "
Book class instance destroyed.
";} } $book = new Book("111111111111");
?>
</source>
Cleaning Up with the __destruct Method (PHP 5 Only)
<source lang="html4strict">
<?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 ); ?>
</source>
Declaring and Using Object Constructors and Destructors
<source lang="html4strict">
<?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(); ?>
</source>
Defining an object destructor
<source lang="html4strict">
class car {
function __destruct() { }
}
</source>
destuctor in action
<source lang="html4strict">
<?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 ); ?>
</source>