views:

260

answers:

3

I had a problem recently with a php project that I finally realised was down to the way I had structured my classes. If I tried to include more than one class in a page and both classes shared the same parent class, the script failed. I've now resolved the issue but was wondering if someone could explain to me exactly why what I was doing wasn't working, cos I haven't quite got my head around it! Here's an illustration of what did NOT work:

class A.
class B extends A.
class C extends A.
class D extends B.
class E extends C.

I require class D and class E and the script fails. If class C does not inherit A then it all works fine. Obviously, it's something to do with requiring class A twice, but could someone explain it in very simple terms for me?!?!?

+3  A: 

Do you have each class in its own file?

Are you using require/include instead of require_once/include_once ? include_once and require_once do not share the same table of included files either, so you have to use one consistently.

Or consistently use the __autoload function in PHP5.

OIS
+2  A: 

You may declare every class only once. If you require the file where your class is defined more than once, the parser encounters the class A, makes an internal lookup and bails: 'Hey, you've already defined that class'. The most simple solution is to put every class into its own file and call require_once instead of require.

soulmerge
I think this might be it... I always used require and not require_once as I didn't really know there was any difference! Each class is in it's own file.
musoNic80
+1  A: 

Any functions or classes defined in included files are declared in the global scope. This is why you are probably getting redeclaration errors. The solution is to use require_once or include_once instead of require or include.

The most elegant way though, is to use a __autoload, but that requires PHP version 5 or later. The only downside to autoloading is that any failure is a fatal error which you can't handle yourself.

nikc