-2

I need to find a way to skip require_once error in case 2 php classes, with same name, are called in a file. I have 2 files a.php and b.php and each of them have class A declared inside. Inside index.php I first include a.php file which has class A declared. Also inside index.php I must include c.php, which inside it has require_once b.php and for this reason I get duplicate classname error and the script is stopped. Can I find a workaround for this? Thanks for your reply


Let me explain it better. Is about Joomla and I build a plugin to overwrite a component models and views. I included my models and views classes in the plugin and Joomla uses them instead of the original component models and views classes. The problem appears when a component module is including the component original models and views classes with require_once. Since my plugin is not using the original models classes, so the file where the original models classes are, is not included inside Joomla, the module require_one is able to include the component model classes, and those classes has the same name as my plugin ones. I can only change my plugin code and classes and not component classes, the second ones.

3 Answers3

4

I need to find a way to skip require_once error in case 2 php classes, with same name, are called in a file.

No you don't. You shouldn't have 2 classes in the same file. Uhhhmm lemme rephrase that. You cannot have two classes with the same name (unless namespaced). But seriously you shouldn't have two classes in 1 file.

I have 2 files a.php and b.php and each of them have class A declared inside.

I guess (/ hope) they are not the same classes because that would violate (rape) the DRY principle.

Can I find a workaround for this?

Don't copy the same class. If both classes are different namespace it. Either the new way with real namespaces or the old way:

namespace Lib\Your\Namespace;

or

class Lib_Your_Namespace
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • I know I must not have 2 classes with the same name, but I can't change the code of b.php or remove it...hoping there's a workaround for this. – user1628151 Aug 27 '12 at 16:30
0

wrap the require call in

if(!class_exists('your_class_name')) {
     require_once('file_name');
}
thelastshadow
  • 3,406
  • 3
  • 33
  • 36
0

I think that the namespace - this is what you need

Viktor Kulikov
  • 269
  • 2
  • 12