Reputation: 8995
If we have two or more classes with the same name, but in different folders, how would one differentiate between them during initialization?
require_once('database.php');
require_once('t/database.php');
$db = new Database(); // I want this to initialize the one in t/database.php
$globalDb = new Database(); // I want this to initialize database.php
Upvotes: 1
Views: 703
Reputation: 11980
This is what Namespaces are for.
But honestly, this sounds like an architectural problem. There are two ways you can approach this. If we were to answer your question as posed, you could solve your problem like so:
database.php
class Database{
// ...
}
t/database.php
namespace T;
class Database{
// ...
}
index.php
require_once('database.php');
require_once('t/database.php');
$db = new T\Database();
$globalDb = new Database();
But judging by your naming conventions, it appears as if you have two separate classes that are intended to interact with either the same - or similar - database instances.
I'm making some assumptions here, but the other way you can set up your logic is to condense your code down to a single Database class and operate on multiple connections over multiple instances.
Consider using dependency injection to manage your connections in a single unified class structure, especially if you're using the same type of RDBMS flavor across all connections.
Consider something like the following naive example:
class Database{
private $conn;
public function __construct(PDO $conn){
$this->conn = $conn;
}
public function select(...$args) { // Select Logic goes here }
public function insert(...$args) { // Insert Logic goes here }
public function update(...$args) { // Update Logic goes here }
public function delete(...$args) { // Delete Logic goes here }
}
It would be possible to operate over multiple connections at once by simply injecting different PDO instances into the same class:
require_once('database.php');
$conn1 = new PDO('mysql:host=localhost;dbname=test1', $user, $pass);
$conn2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass);
$db1 = new Database($conn1);
$db2 = new Database($conn2);
So while the first example may address your question directly, you may want to rethink your architecture if I'm on the right track with my second example.
And to echo everyone else, you should seriously consider using a proper Autoloader. Look into Composer and Autoloading - specifically PSR-4.
Upvotes: 2
Reputation:
If we have two or more classes with the same name, but in different folders, how would one differentiate between them during initialization?
Don't do that. Loading the PHP file which contains the second definition will throw an error:
Fatal error: Cannot declare class Database, because the name is already in use
You will need to rename one of the classes.
As an aside, you may want to consider using an autoloader in your application instead of calling require()
manually.
Upvotes: 0