tags:

views:

42

answers:

2

In my project, say I am instantiating a class named SubClass, which extends an abstract class named AbstractClass. At the top of my files I include a file named bootstrap.inc, which includes AbstractClass in every file. Then, when I need it, I include SubClass which does not contain an include to AbstractClass.

If I include AbstractClass in the files of classes that extend it (such as SubClass), sometimes I am using multiple sub-classes in one file and will get an error. I would rather not include AbstractClass in every file via the bootstrap, since I am not always using it, but cannot think of a way to avoid this.

I have been advised that using include_once() is a sign of poor design, so have avoided that, although it would be one solution.

Is there an alternative method to include_once()?

+4  A: 

First off - it's generally a good idea to stick to one class per file. If you're worried about performance, you're being paranoid. In production, you can always turn on APC with stat off.

Secondly - there's nothing wrong with include_once/require_once.

Unless you're going to set up some fancy autoloading magic, just stick to one class per file.

Absent some specific concern (that is, something articulable that you actually understand, not just some rumor you heard), the following pattern is perfectly fine:

<?PHP
require_once 'MyAbstract.class.php';

class Concrete extends MyAbstract {
 //...
}
// end-of-file
timdev
Adding to this answer, "autoloading magic" doesn't have to be fancy. Assuming everything's in the same directory. it'd just be: `function __autoload($class) { require $class.'.inc'; }`This also forces the convention that a file bears the same name as the class it holds, which is a good habit to get into.
Daniel
@Daniel - Absolutely right, autoloading can be handy, and easy to implement. I just didn't want to distract from my "simple is at least fine, and probably good" message. :-)
timdev
@timdev - thanks for your answer. Is it common to see parent classes included using `require_once` throughout class files, as seen in your example?
letseatfood
Absolutely - it's the most common approach I've seen, anyway. Each class file require_once's it's immediate dependencies.
timdev
+2  A: 

PHP's Autoloading mechanism could be ideal for you.

That said, there's nothing wrong with include_once(). What that person talking about a design flaw was probably referring to is that a code flow that includes the same file more than once (thus making include_once() necessary over include() is most likely badly designed.

Pekka