PDO:在哪里声明数据库连接?

I've just started using PDO and was wondering how best to declare the database connection?

Would it best practice to create a script as follows, called config.php for example

config.php

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Then have example.class.php

<?php
include config.php;
class Example {
    public function fetch() {
          $data = $dbh->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));
          // do stuff
    }

}
?>

And do this for all my classes? Or would this make multiple connections? I want to have as few connections as possible.

You're close but your fetch function won't work because $dbh is outside its scope.

You could globalize it but a better solution is to pass your handler to your class upon instantiation

class Example {
    /** @var \PDO */
    protected $pdo;

    public function __construct(\PDO $pdo) {
         $this->pdo = $pdo;
    }
}
$class = new Example($dbh);

This is a best practice. This way the logistics of setting up and naming your db pointer are irrelevant. Your class defines how it's going to receive it and you use the instance of the pointer you were passed.

Your example looks good, it would only create one persistent connection.

However, you should pass in $dbh to the __construct of Example, and do $this->dbh later instead of relying on $dbh being a global.

To avoid needing to do that in all your classes that need to access, you could either implement a class that deals with the DB and other classes inherit from, or implement a Trait.

To keep clean and organized code, you can create a "DbManager" class and instantiate the PDO, create query and other methods, etc... You can use the config.php to store your application configuration.