I have a PHP class that uses a MySQLi prepared statement to load some data like this:
class MyClass {
public $a, $bla;
public load(&$mysqli) {
$s = $mysqli->prepare('SELECT a FROM x WHERE y = ?');
$s->bind_param('s', $this->bla);
$s->bind_result($this->a);
if($s->execute()) {
if($s->fetch()) {
$s->free_result();
}
}
}
}
However, this means that for every object of MyClass on which I call the load() function I will prepare a new statement, which seems inefficient.
My idea for reusing the prepared statement would be to do something like this:
class MyClass {
public $a, $bla;
private static $my_s;
public load(&$mysqli) {
if(!self::$my_s) {
self::$my_s = $mysqli->prepare('SELECT a FROM x WHERE y = ?');
}
$s = self::$my_s;
$s->bind_param('s', $this->bla);
$s->bind_result($this->a);
if($s->execute()) {
if($s->fetch()) {
$s->free_result();
}
}
}
}
So save the statement as a static member variable. This way, the statement should be prepared the first time I call load(), after which it will be reused by all objects of the same class.
Is this a valid approach? Is there a better way?