note 68142 deleted from function.mysqli-free-result by hholzgra

From: Date: Sat, 29 Sep 2007 10:55:49 +0000
Subject: note 68142 deleted from function.mysqli-free-result by hholzgra
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-130918@lists.php.net to get a copy of this message
Note Submitter: lucky760 at yahoo dot com ---- Here's a method I wrote to simplify the automatic freeing of mysqli_result objects when all references disappear. The beauty of it is that it's presence is tranparent to the user because it acts exactly like a mysqli_result object. Also, jon at fuck dot org, you don't have to pass the resultmode ("flag") around because it's accessible with the mysqli_result object (the 'type' property). <?php final class MysqliResultWrapper { private $m_mysqli_result; public function __construct($i_result) { if (isset($i_result) && $i_result instanceof mysqli_result) $this->m_mysqli_result = $i_result; else throw new Exception(__CLASS__ . ' instantiated with ' . gettype($i_result)); } // automatically disappear the mysqli_result when all references to us vanish public function __destruct() { if (isset($this->m_mysqli_result)) $this->m_mysqli_result->free(); } // pass back mysqli_result properties public function __get($i_varname) { if (!isset($this->m_mysqli_result)) return NULL; /** * Do you know a generic way for PHP to retrieve a member * function instead of this ugly switch? */ switch ($i_varname) { case 'current_field': return $this->m_mysqli_result->current_field; case 'field_count': return $this->m_mysqli_result->field_count; case 'lengths': return $this->m_mysqli_result->lengths; case 'num_rows': return $this->m_mysqli_result->num_rows; case 'type': return $this->m_mysqli_result->type; } throw new Exception('Trying to get non-existent mysqli property ' . $i_varname); } // forward mysqli_result function calls public function __call($i_funcname, $i_arguments) { call_user_func_array(array(&$this->m_mysqli_result, $i_funcname), $i_arguments); } } ?> Example usage: <?php function some_query_func($i_query, $i_resultmode = MYSQLI_STORE_RESULT) { $conn = getExistingMysqliObjectFromSomePlace(); $result = @$conn->query($i_query, $i_resultmode); if ($result === FALSE || $result === NULL) throw new Exception($conn->error); return $result instanceof mysqli_result ? new MysqliResultWrapper($result) : $result; } $result = some_query_func($query);// unhandled Exception thrown on failure if ($result->num_rows > 0)// calls __get() while ($assoc = $result->fetch_assoc())// calls __call() ;// ... ?>

« previous php.notes (#130918) next »