I have a directory tree where in different sub-directories I have a lot of classes with the same name. There is a strong intention to not edit these classes.
I'm looking for a way to load one class and after using it and destroying its instance load another with exactly the same name. Then use it, destroy its instance and repeat that process.
I thought some possible solutions:
For the 3rd I thought this could be useful: Componere or Runkit or Classkit but don't have any experience with them.
Do you have any other ideas or perhaps some solutions? Did you use componere or Runkit / Classkit and can say they suit the job? maybe there are other options?
Perhaps there is a OOP design pattern that covers this issue but I'm not familiar with it.
Example code:
<?php
#------------------------------------
//path Foo/Bar.php
/* class is without a namespace or have the same
as Baz/Bar.php */
class Bar
{
public function getName() : string
{
return 'Foo/Bar';
}
}
#------------------------------------
//path Baz/Bar.php
/* class is without a namespace or have the same
as Foo/Bar.php */
class Bar
{
public function getName() : string
{
return 'Baz/Bar';
}
}
#------------------------------------
//path ./Execute.php
$paths = [
'Foo/Bar.php',
'Baz/Bar.php'
];
$results = [];
foreach ($paths as $path) {
//how to create instance of class Bar in Foo/Bar.php and then in Baz/Bar.php
//without PHP Fatal error: Cannot declare class...
$classDynamic = ...
$results[] = $classDynamic->getName();
unset($classDynamic);
}
var_export($results)
/**
* prints
* array('Foo/Bar', 'Baz/Bar')
*/
I do not think there is a way to unset a class once it has been defined and as they share the same namespace they will error out. but you could get the effect you wanted as follows
class Bar
{
$myname = "";
function __construct($setname="")
{
$this->myname = $setname;
}
function getName()
{
return $myname;
}
}
$paths = array('Foo/Bar','Baz/Bar');
$results = array();
foreach($paths as $p)
{
$bit = new Bar($p);
$results[] = $bit->getName();
}
var_export($results);