Now I am reading the book "PHP5 for Professionals", this is the 2006 edition. And in one example, they throw an exception in the destructor, for a long time I did not understand why my last exception in the destructor did not work, then I looked for it and found that in PHP => 5.3 it is not available to throw an exception in the destructor. So, how best to do this if in the destructor I update my database if the variable $needsUpdate = true; and close the database connection, so I wanted to throw an exception if the database could not be updated. For example, I throw an exception in my DB class, but I catch them in the main file, for example:
Custom Widget Class:
class Widget { private $_id; private $_name; private $_description; private $_hDB; private $_needsUpdating = false; public function __construct($widgetID) { $this->_hDB = new mysqli('localhost', 'phpbook', 'Un+)J=<AaH', 'phpbook'); if (! $this->_hDB) { throw new Exception(' '); } $sql = "SELECT `name`, `description` FROM widgets WHERE id = '$widgetID'"; $rs = $this->_hDB->query($sql); if (! $rs) { throw new Exception(" "); } if (! $rs->num_rows) { throw new Exception(" "); } $data = $rs->fetch_assoc(); $this->_id = $widgetID; $this->_name = $data['name']; $this->_description = $data['description']; } public function getName() { return $this->_name; } public function getDescription() { return $this->_description; } public function setName($name) { $this->_name = $name; $this->_needsUpdating = true; } public function setDescription($description) { $this->_description = $description; $this->_needsUpdating = true; } public function __destruct() { if (! $this->_needsUpdating) { return; } $sql = 'UPDAT2E `widgets` SET'; $sql .= ' `name` = "' . $this->_hDB->real_escape_string($this->_name) . '",'; $sql .= ' `description` = "' . $this->_hDB->real_escape_string($this->_description) . '" '; $sql .= 'WHERE id = ' . $this->_id; $rs = $this->_hDB->query($sql); if (! $rs) { throw new Exception(" "); } $this->_hDB->close(); } }
And this is the main file.
try { $widget = new Widget(2); echo "Name: " . $widget->getName() . "<br />\n"; echo "Description: " . $widget->getDescription() . "<br />\n"; $widget->setName("Iphone 4 / 64GB"); $widget->setDescription("New Phone, black color, blablabla"); } catch (Exception $e) { die("An error has occurred: " . $e->getMessage()); }
And the last exception in __destruct() does not work.
So, is there a good way to throw an exception if the update database fails? Or is there another right way, and I didn’t understand anything?
source share