I am coding my first object factory, and I am wondering if there any any drawbacks to passing one object into another when creating the second object, and then saving the first object within the second for use later?
Example:
class main
{
public $connection = array();
// various other useful functions that should be loaded on every page here
// these other functions would be convenient to have avail for
// new objects in different classes
function dbconnect($db) {
if(!isset($this->connection[$db])) {
switch($db) {
case "users":
$connection = @mysql_connect(info,info,info);
$db_select = @mysql_select_db(info,$connection);
$this->connection[$db] = $connection;
break;
case "ads":
$connection = mysql_connect(info,info,info);
$db_select = mysql_select_db(info,$connection);
$this->connection[$db] = $connection;
break;
default:
die($db . " is not a recognized database.");
break;
}
}
return $this->connection[$db];
}
// note how i pass $this into the new object in this function
function create($class,$params=null) {
if(!class_exists($class) && !$this->load($class)) {
die($class . " is not a recognized class.");
}else{
return new $class($this,$params);
}
}
function load($file) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/classes/" . $file . ".class.php";
if(file_exists($file)) {
return require_once($file);
}else{
return false;
}
}
}
class secondary {
private $connection;
private $mainObj;
private $params;
function __construct($mainObj,$params) {
$this->mainObj = $mainObj;
$this->params = $params;
$this->connection = $mainObj->dbconnect('users');
}
}
As you see here, any class created by the factory conveniently has the ability to connect to the MySQL db if the class requires it (and other common/useful functions) ... without having to use globals, or pass many things in.
Is this a stable way? I am new, and could use some good theory/schooling on why this is wrong - if it is.