When to instantiate a new class
| From: | Ramiro Barrantes | Date: | Wed, 17 Jun 2015 20:56:03 +0000 |
| Subject: | When to instantiate a new class | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-324953@lists.php.net to get a copy of this message | ||
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