Some confusion regarding object creation in static function
Hi guys :wave:
I have been going through some piece of code and got confused at a certain point. The below is a piece of code:
PHP Code:
class DataManager
{
private static function _connect()
{
return new PDO('mysql:host=localhost;dbname=sample', 'root','');
}
public static function fetch_users()
{
$db = self::_connect();
$st = $db->query("SELECT * FROM users");
//....
}
public static function func2()
{
$db = self::_connect();
$st = $db->query("SELECT * FROM users");
//....
}
public static function func2()
{
$db = self::_connect();
$st = $db->query("SELECT * FROM users");
//....
}
//and so on..
}
Isn't that a bad practice ? I mean, each time when a member function is executed, the connect() function is called which will return a NEW PDO object. So, new PDO objects are created each time.
Am I correct ? :confused:
Thanks :wave:
Re: Some confusion regarding object creation in static function
Yes, this is bad practice. _connect() should instead check if a connection object already exists, and return it if so, otherwise create a new one only as needed.
Re: Some confusion regarding object creation in static function
Quote:
Originally Posted by
SambaNeko
Yes, this is bad practice. _connect() should instead check if a connection object already exists, and return it if so, otherwise create a new one only as needed.
This is a common pattern.
I prefer just to create it anyway:
PHP Code:
class DataManager
{
public static function connect()
{
return new PDO('mysql:host=localhost;dbname=sample', 'root','');
}
public static function fetch_users()
{
$st = $db->query("SELECT * FROM users");
//....
}
//...
}
DataManager::connect();
Also, I prefer using prepared statements wherever possible:
PHP Code:
public static function fetch_users()
{
static $stmt;
if ($stmt === null)
$stmt = $db->prepare('SELECT * FROM users');
$st = $stmt->execute();
//....
}
This is overkill for a simple query such as that one, but once you add parameters the benefits quickly outweight the cost.
Notice that the static keyword has a different meaning within a function: it creates a variable which is local to the function, but which retains its value between calls. Since this function is a class member, it is equivalent to creating a static class variable, but with an additional scope restriction.
Re: Some confusion regarding object creation in static function
Thanks for the clarification :wave:
I got this piece of code from here: http://www.phpvault.net/
He had posted some video tutorials on youtube and the sourcecodes were uploaded in that site.