Thank you so much for this! Will try it. ________________________________________ From: Ashley Sheridan [ash@xxxxxxxxxxxxxxxxxxxx] Sent: Thursday, June 18, 2015 4:28 AM To: Ramiro Barrantes; php-general@xxxxxxxxxxxxx Subject: Re: When to instantiate a new class On 17 June 2015 21:56:03 BST, Ramiro Barrantes <ramiro@xxxxxxxxxxxxxxxxxxxxx> wrote: >Hello, > >This is a very basic question, i just don't know php well enough to >know what's best. I have a screen class and a database class. The >screen class handles everything related to what goes on the screen, but >its many functions often need to use the database class to get relevant >information. The question I have is: > >How often should I instantiate the database class? Should I do it once >with say, the constructor of the screen class? Or with the specific >method, or pass it as a variable? > >For example: > >INSTANTIATING WITHIN EACH FUNCTION >function method($variable) { > $db = new databaseInterface(): > ... >} > >or > >PASSING IT AS A VARIABLE FOR EACH FUNCTION >function method($variable,$db) { > ... >} > >or > >CREATING IT AS PART OF THE SCREEN CONSTRUCTOR AND ACCESSING IT WITH A >"getter" >class screen { > private $db; > function construct() { > $db=new databaseInterface(); > } > > function getDatabaseInstance() { > return($db); > } >} > >Thanks in advance, >Ramiro I would actually use a Singleton pattern for the database class, and then you can call that from within each method of your screen class. It's a fairly typical practice for database classes to ensure you're not creating too many connections to it (which can be a blocker later on if many people are using your website) Ash -- Sent from my Android device with K-9 Mail. Please excuse my brevity. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php