note 86718 added to mysqli-result.fetch-object

From: Date: Fri, 31 Oct 2008 14:43:27 +0000
Subject: note 86718 added to mysqli-result.fetch-object
Groups: php.notes 
Request: Send a blank email to php-notes+get-145997@lists.php.net to get a copy of this message
As the description says, you can give a class name as first optional parameter, that should be instantiated and as second parameter an array with values that should be passed to the constructor. However, the assignements are done, before the constructor is executed! Check out this example: <?php class MyCuteObject { protected $id = -1; public function __construct($id) { //throw new Exception("Headache"); $this->id = $id; echo("\nInstiantiate with ID:$id\n\n"); } public function __destruct() { echo("\n\ndestroy with ID:" . $this->id . "\n\n"); } public function __set($name, $value) { $this->$name = $value; echo($this->id . ": " . '$this->' . "$name is set to $value\n"); } public function id() { echo("i have ID: " . $this->id . "\n"); } } $dbh = new mysqli($host, $user, $password, $database); $sql = "SELECT * FROM Books WHERE Author LIKE 'Stephen King'"; $i = 0; if($res = $dbh->query($sql)) { while($obj[] = $res->fetch_object("MyCuteObject", array($i))) { $i++; } } echo("\n\n$i Entries\n\n"); $obj[1]->id(); $dbh->close(); ?> You will get output like this: ###########begin of output -1: $this->Author is set to Stephen King -1: $this->Title is set to Wahn Instiantiate with ID:0 -1: $this->Author is set to Stephen King -1: $this->Title is set to Puls Instiantiate with ID:1 2 Entries i have ID: 1 destroy with ID:0 destroy with ID:1 ###########end of output If you uncomment the Exception you will be assured that the assignements are done: ###########begin of output -1: $this->Author ist nun Stephen King -1: $this->Title ist nun Wahn destroy with ID:-1 Exception: Headache in /my/wonderful/patho/to/project/test.dbobj.php on line 6 ###########end of output I am wondering wether this behaviour is wanted or rather a bug? ---- Server IP: 217.160.72.57 Probable Submitter: 195.226.112.5 ---- Manual Page -- http://www.php.net/manual/en/mysqli-result.fetch-object.php Edit -- https://master.php.net/note/edit/86718 Del: integrated -- https://master.php.net/note/delete/86718/integrated Del: useless -- https://master.php.net/note/delete/86718/useless Del: bad code -- https://master.php.net/note/delete/86718/bad+code Del: spam -- https://master.php.net/note/delete/86718/spam Del: non-english -- https://master.php.net/note/delete/86718/non-english Del: in docs -- https://master.php.net/note/delete/86718/in+docs Del: other reasons-- https://master.php.net/note/delete/86718 Reject -- https://master.php.net/note/reject/86718 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#145997) next »