|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-09-10 11:45 UTC] waps at pisem dot net
Description:
------------
Incorrect creating user object: set data before call constructor method.
Reproduce code:
---------------
---
From manual page: pdostatement.fetchobject
---
class Product {
public function __construct() {
echo 'create object, ';
}
public function __set($offset, $value) {
echo 'set value, ';
}
}
// fetch object
$stmt->fetchObject('Product', array());
Expected result:
----------------
Expected result: create object, set value,
Actual result:
--------------
Actual result: set value, create object,
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 20:00:01 2025 UTC |
Confirmed. If the constructor sets default values for some fields, as is typical, the constructor will overwrite the values just retrieved from the database. <?php class Book { function __construct() { $this->title = "Default"; } } $pdo = new PDO('mysql:dbname=books', 'root'); $statement = $pdo->prepare('SELECT * FROM book WHERE title=\'Peopleware\''); $statement->execute(); $obj = $statement->fetchObject('Book'); echo $obj->title; // Expected: Peopleware. Actual: Default ?>Thats evil!... My code with an Ugly solution! <?php class TestObject { public function __construct($id=0, $name='', $mail=''){ // if (isset($this->id)) return; // Ugly solution necessary atm to bypass the problem!. $this->id = $id; $this->name = $nome; $this->mail = $mail; } } $dbh = new PDO('sqlite:'.dirname(__FILE__).'/foo.db'); $qr = $dbh->query("SELECT 1 as id, 'test' as name, 'abc@def.com' as mail"); $x = $qr->fetchObject('TestObject'); print_r($x); Expected: TestObject Object ( [id] => 1 [name] => test [mail] => abc@def.com ) Actual Result: TestObject Object ( [id] => 0 [name] => [mail] => )