How can the database connection object $dbh be properly passed into a class in PHP for method execution?

When passing the database connection object $dbh into a class in PHP for method execution, you can do so by either passing it as a parameter in the class constructor or setting it as a property of the class. This allows the class to utilize the database connection for executing queries within its methods.

class MyClass {
    private $dbh;

    public function __construct($dbh) {
        $this->dbh = $dbh;
    }

    public function executeQuery() {
        // Example query execution using $this->dbh
        $query = "SELECT * FROM table";
        $stmt = $this->dbh->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

// Usage
$dbh = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$myClass = new MyClass($dbh);
$results = $myClass->executeQuery();