将 prepare() 返回的 PDOStatement 保存到某个类变量然后重用该语句对象而不是在执行相同调用时重新准备是否有效?
Class QueryClass {
public static $getSomeData;
}
Class Foo {
$pdo = $pdo (PDO)
$id;
$first_name;
$last_name;
$email;
$city;
public function __construct(PDO $pdo, $id) {
$this->pdo = $pdo;
$this->id = $id;
}
public function searchDB(Array $find) {
$query = "SELECT " . prepare_array($find);
$query .= "FROM some_database ";
$query .= "WHERE id = ?";
// Option 1.) Prepare Normally
$statement = $this->pdo->prepare($query);
// Option 2.) Prepare conditionally depending on what the query
// was the last time the method was called. So it should only be called
// when either (A) The method has never been called OR (B) The user
// has changed the query string by entering different data in the
// $find parameter
if (!QueryClass::$getSomeData instanceof PDOStatement
|| QueryClas::$getSomeData->queryString != $query)
{
QueryClass::$getSomeData = $this->pdo->prepare($query);
}
// Executing Option 1
$statement->execute(Array($this->id));
// Exectuting Option 2
QueryClass::$getSomeData->execute(Array($this->id));
}
}
// And then using like this (I know that I havent actually created the PDO, just assume
// that I'm providing it). The second searchDB() call should use the same PDOStatement
// object created when the first object used it
$var = new Foo($pdo, 5);
$var2 = new Foo($pdo, 10);
$var->searchDB(Array('first_name', 'last_name', 'email'));
$var2->searchDB(Array('first_name', 'last_name', 'email'));
// Then makeing a call like this would cause the method to re-prepare the
// PDOStatement because the params provided are different
$var2->searchDB(Array('first_name', 'city'));
这是否比每次调用查询或方法时都准备一条新语句更有效?