Sahin Urkin
Sahin Urkin

Reputation: 279

How to include different classes with same name?

Here is the problem, I have a script test.php there is a loop inside it in this loop I want to use 4 classes (separate files) from different folders (they are pdf print classes, but everyone is different by the others), all of them are with same names PdfCreator I want every iteration to include/require (use) different class:

$brokerTables = ['test1' => 'broker_report', 'test2' => 'choice_report', 'test3' => 'odit_report', 'test4' => 'other_insurer_report'];

foreach ($brokerTables as $folder => $table) {

    require_once($folder . '/classes/' . $brokerTables[$folder]);

    $pdfdoc = new PdfCreator($this->conn);

    // use $pdfdoc..

};

Is there a way to do it ? without rename of classes ?

Error is Cannot declare class PdfCreator, because the name is already in use

Upvotes: 0

Views: 530

Answers (1)

IMSoP
IMSoP

Reputation: 97688

The fundamental answer is that you can't. Class names in PHP are unique, and outside of some exotic extension that should never be used in production, cannot be "undeclared" or renamed.

So, you'll need to come up with a different program design. For instance, you could use the folder name as part of the class name, or more logically as a namespace, so that each name is unique. You'll then need to define the class name dynamically to create the object, like this:

$className = "\\MyTopLevelNamespace\\{$folder}\\PdfCreator";
$pdfdoc = new $className($this->conn);

Note that namespaces aren't necessary here, you can use any naming scheme you like, to make the class names unique, e.g.

$className = "{$folder}_PdfCreator";
$pdfdoc = new $className($this->conn);

An additional advantage of using the folder somewhere in the class name or namespace is that you can use an autoloader to find the definition, rather than explicitly writing the require_once statement each time you need the class.

Upvotes: 2

Related Questions