It could be done in the constructor, but it still might not be what you need just by including it if you depend on certain variables that it sets, as they would be local to that constructor method. You would need to copy them into class variables.
A more modular solution might be to turn that database connection stuff into its own class, then pass an instantiation of it to your other class.
DbConnect.php:
PHP Code:
class DbConnect
{
private $connection;
private $host = 'localhost';
private $user = 'root';
private $pwd = 'abcd1234';
private $databae = 'my_database';
public function __construct()
{
$this->connection = mysql_connect($this->host, $this->user, $this->pwd);
if($this->connection != false)
{
$result = mysql_select_db($this->database, $this->connection);
if($result == false)
{
throw new Exception("Database select failed");
}
}
else
{
throw new Exception ('Database connect failed');
}
}
public function connx()
{
return $this->connection;
}
}
DoSomeDbStuff.php:
PHP Code:
class DoSomeDbStuff
{
private $db;
public function __construct(DbConnect $db) // Type-hinting
{
$this->db = $db;
}
public function foo()
{
$result = mysql_query('SELECT * FROM anything', $this->db->connx());
return $result;
}
}
test.php:
PHP Code:
require_once 'DbConnect.php';
require_once 'DoSomeDbStuff.php';
try
{
$db = new DbConnect();
}
catch(Exception $e)
{
die('Oh crap!');
}
$test = new DoSomeDbStuff($db);
$queryResult = $test->foo();
The above is crude and not necessarily how I'd do it, just a quick-and-dirty example to hopefully give you some food for thought.
Bookmarks