How can I just return objects to PDO?

The first launch of PDO.

$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_INTO, new animals);

foreach($stmt as $animals)
{
    echo $animals->name;
}

If I skip the method setFetchMode(), then I need to call $animals["name"], which I don't want.

But I do not want to call setFetchMode()for every request that I make.

Is there a way to set FetchMode by default? Or some other way to make objects query()return with one global setting.

+3
source share
2 answers

Perhaps you could try extending the PDO class to automatically call a function for you ... in short:

class myPDO extends PDO
{
   function animalQuery ($ sql)
   {
     $ result = parent :: query ($ sql);
     $result->setFetchMode(PDO::FETCH_INTO, new animals);
     return $result;
   }

//   // useful if you have different classes
//   function vegetableQuery($sql)
//   {
//     $result = parent::query($sql);
//     $result->setFetchMode(PDO::FETCH_INTO, new vegetables);
//     return $result;
//   }
}

$dbh = new myPDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->animalQuery("SELECT * FROM animals");

foreach($stmt as $animals)
{
    echo $animals->name;
}
+6

PDO , , . , , , , , ,

  $connection = new PDO($connection_string);
  //PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set 
  $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 

. , , .


:

while($dataObj = ...) {
 $animal = new Animal($dataObj);
}

, , : http://www.php.net/manual/en/pdo.query.php , , , .

+2

Source: https://habr.com/ru/post/1706392/


All Articles