note 117730 added to pdostatement.fetchobject
| From: | beinghavingbreackfast at gmail dot com | Date: | Wed, 29 Jul 2015 20:50:29 +0000 |
| Subject: | note 117730 added to pdostatement.fetchobject | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-203216@lists.php.net to get a copy of this message | ||
It should be mentioned that this method can set even non-public properties. It may sound strange but
it can actually be very useful when creating an object based on mysql result.
Consider a User class:
<?php
class User {
// Private properties
private $id, $name;
private function __construct () {}
public static function load_by_id ($id) {
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE id=?');
$stmt->execute([$id]);
return $stmt->fetchObject(__CLASS__);
}
/* same method can be written with the "name" column/property */
}
$user = User::load_by_id(1);
var_dump($user);
?>
fetchObject() doesn't care about properties being public or not. It just passes the result to
the object. Output is like:
object(User)#3 (2) {
["id":"User":private]=>
string(1) "1"
["name":"User":private]=>
string(10) "John Smith"
}
----
Server IP: 72.52.91.14
Probable Submitter: 95.43.74.221
----
Manual Page -- http://php.net/manual/en/pdostatement.fetchobject.php
Edit -- https://master.php.net/note/edit/117730
Del: integrated -- https://master.php.net/note/delete/117730/integrated
Del: useless -- https://master.php.net/note/delete/117730/useless
Del: bad code -- https://master.php.net/note/delete/117730/bad+code
Del: spam -- https://master.php.net/note/delete/117730/spam
Del: non-english -- https://master.php.net/note/delete/117730/non-english
Del: in docs -- https://master.php.net/note/delete/117730/in+docs
Del: other reasons-- https://master.php.net/note/delete/117730
Reject -- https://master.php.net/note/reject/117730
Search -- https://master.php.net/manage/user-notes.php