Use Query in class
Queries can be fetched into objects based on custom classes. For example, if we have a class named ExampleClass, the following query will return objects of type ExampleClass.
$result = $connection->query("SELECT id, title FROM {example_table}", [], [ 'fetch' => 'ExampleClass', ]);
If the class has a __construct() method, objects will be created, properties will be added to the object, and then the __construct() method will be called. For example, if you have the following class and query:
class ExampleClass { function __construct() { // Do something } } $result = $connection->query("SELECT id, title FROM {example_table}", [], [ 'fetch' => 'ExampleClass', ]);
The object will be created, properties id and title will be added to the object, and then __construct() will be executed. The order of these events is related to a bug in PHP for versions less than 5.2.
If your object has a __construct() method that must be executed before properties are added to the object, the following example shows how to do it.
$result = $connection->query("SELECT id, title FROM {example_table}"); foreach ($result->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'ExampleClass') as $record) { // Do something }
The arguments passed to fetchAll can be used in the same way. PDO::FETCH_CLASS tells fetchAll to take the returned result set and add the values as properties to an object of type ExampleClass (second argument). PDO::FETCH_PROPS_LATE tells fetchAll to add the result set as properties to the object after calling __construct().
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.