Using two class with the same name
I have two PHP apps which have twh开发者_JAVA百科o class with the same name. - app1 with a class "Project" - app2 with a class "Project"
I have to use classes of the first app in the second one, but two class with one name cause an error ("PHP Fatal error: Cannot redeclare class Project ...").
I can't change class names. I have to use PHP 5.2 (no namespace in PHP 5.2).
Is there a solution ?
May be :
- use the class Project
- undef this class (kind of "unset Project", is it possible with PHP ?)
- include() the 2nd class
- use the 2nd class
I don't know if it's possible with PHP (don't find any ressource about this) and I don't know a better way to manage this ...
I had this problem recently, with (embarrassingly) Joomla. I needed to find the versions of two different installations with one script, by loading up their two "version.php" files and then reading the class properties. But, of course, they're both called "JVersion", and it's impossible to require() both version.php files because of it.
After much thought, I realized eval() could take the place of require(). So I just read in the contents of the version.php files and change the names of the classes, then eval() that text, and then I can access both classes with different names. I bet you'd like some code. Here's what I ended up with...
$v15_txt=file_get_contents($old_dir.'/libraries/joomla/version.php');
$v15_txt=preg_replace('/class JVersion/i', 'class JVersion15', $v15_txt);
eval('?>'.$v15_txt);
$jvold=new JVersion15;
$old_version = $jvold->RELEASE.'.'.$jvold->DEV_LEVEL;
$v25_txt=file_get_contents($new_dir.'/libraries/cms/version/version.php');
$v25_txt=preg_replace('/class JVersion/i', 'class JVersion25', $v25_txt);
eval('?>'.$v25_txt);
$jvnew=new JVersion25;
$new_version = $jvnew->RELEASE.'.'.$jvnew->DEV_LEVEL;
Just modify it so it loads the right two files for your needs and renames them as required. Sorry you had to wait over a year for it. :-)
It's hard to believe PHP doesn't have some kind of "undeclare($classname)" function built-in. I couldn't even solve this with namespacing, because that requires changing the original two files. Sometimes ya just gotta think outside the framework.
Stop.
Whatever you are doing is wrong. Backup. Re-evaluate what you are doing and why.
If after that, you still need to do this. Pick an app, and do a find and replace on that class name in the app. If it was well designed, it should be unique and easy to do.
Document the hell out of the fact that you did this in whatever external documentation you are using.
精彩评论