|
-
Nov 9th, 2011, 07:47 AM
#1
If my post was helpful to you, then express your gratitude using Rate this Post. 
And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet
Social Group: VBForums - Developers from India
Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...
-
Nov 9th, 2011, 03:22 PM
#2
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.
-
Nov 9th, 2011, 06:35 PM
#3
Re: Some confusion regarding object creation in static function
 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.
Last edited by penagate; Nov 9th, 2011 at 06:41 PM.
-
Nov 10th, 2011, 12:27 AM
#4
Re: Some confusion regarding object creation in static function
Thanks for the clarification 
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.
If my post was helpful to you, then express your gratitude using Rate this Post. 
And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet
Social Group: VBForums - Developers from India
Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|