Current Location: Home> Latest Articles> Return object customization using anonymous class via PDOStatement::fetchObject

Return object customization using anonymous class via PDOStatement::fetchObject

gitbox 2025-05-29

In PHP, PDO is a powerful and flexible database access tool. It provides multiple methods to execute SQL queries and process the returned data through the PDOStatement object. In this article, we will explore how to use the PDOStatement::fetchObject method combined with anonymous classes to customize the return object of the database query result.

What is PDOStatement::fetchObject?

PDOStatement::fetchObject is a method provided by PDO to convert each row of data in the query result into an object. By default, it converts each row of the result set into a standard PHP object (stdClass). However, if we want to customize the returned object according to our needs, we can do it through fetchObject .

Customize the returned object using anonymous class

PHP 7 introduces the concept of anonymous classes, allowing us to create classes without explicitly defining the class name. This provides a lot of flexibility in returning specific custom objects in the query results. We can use anonymous classes in combination with PDOStatement::fetchObject to implement customization of returned objects.

Example: Return database query results through anonymous class

Suppose we have a database table users that contains id , name and email fields. We will execute the query using PDO and customize the returned object format through an anonymous class.

 <?php
// Configure database connections
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'root';
$password = '';

try {
    // create PDO Example
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Execute a query
    $stmt = $pdo->query("SELECT id, name, email FROM users");

    // use fetchObject and anonymous classes return results
    while ($user = $stmt->fetchObject(function($data) {
        // Return a custom anonymous class object
        return new class($data) {
            public $id;
            public $name;
            public $email;

            public function __construct($data) {
                $this->id = $data->id;
                $this->name = $data->name;
                $this->email = $data->email;
            }

            // Add a custom method
            public function getFullName() {
                return strtoupper($this->name);
            }
        };
    })) {
        // Print information for each user
        echo "User ID: {$user->id}, Name: {$user->getFullName()}, Email: {$user->email}\n";
    }

} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>

Code parsing

  1. Database connection : Create a database connection instance through new PDO() and set the error mode to PDO::ERRMODE_EXCEPTION to throw an exception.

  2. Query execution : We use the $pdo->query() method to execute SQL query and select the id , name and email fields from the users table.

  3. Custom anonymous class : In the fetchObject method, we pass in an anonymous class constructor, which accepts each row of data and creates a custom object based on the query results.

  4. Custom methods : In an anonymous class, we can define some custom methods, such as getFullName() , which returns the capitalization of the user's name.

  5. Output result : Obtain user data one by one through a while loop, and print each user's id , name (processed by getFullName() ) and email .

Advantages of using fetchObject

  • High flexibility : With anonymous classes, you can flexibly customize the returned objects as needed, and even add extra methods to each query.

  • Simplicity : The code is relatively concise, and there is no need to explicitly define a class to handle each query result, reducing boilerplate code.

  • Extensibility : You can modify anonymous classes at any time and add new attributes and methods without changing the query logic or creating new class files.