views:

112

answers:

2

Simple question. Why use require_once to include classes that you use within a file? For example, if I create a class that extends Zend_Db_Table_Abstract, I don't really need to have this in the class declaration file:

require_once "Zend/Db/Table/Select.php";

They are included by the auto-loader anyway. Is there a performance gain for explicitly declaring the "imports"? Is it for unit testing?

+6  A: 

Simple Answer: If you aren't using the autoloader, the functionality will not break.

Its not necessary to do this in your project if you know for a fact you will be using the autoloader, but if you are working on a framework (like Zend) that will be used by other developers as well, you will want to have re-usability with least amount of compatibility issues, therefore you really should require explicit dependencies.

Another benefit is that it helps you see when your classes are becoming dependent on too many other classes. This helps you keep your coupling to a minimum while designing your objects.

An example from Zend/Db/Table/Select.php

/**
 * @see Zend_Db_Select
 */
require_once 'Zend/Db/Select.php';


/**
 * @see Zend_Db_Table_Abstract
 */
require_once 'Zend/Db/Table/Abstract.php';
gnarf
Oops, yeah, that was a typo. OK, that makes sense. So, if, for example, I were to write a separate bootstrap for a Zend_Amf implementation...if that didn't use the autoloader, things might break. Great answer.
Typeoneerror
The added note about coupling is a very good one. After I went back and retroactively popped in the requires for some classes, I definitely noted that some were getting heavy. I also noticed that a lot of the Zend Framework itself does not have explicit requires.
Typeoneerror
It may be worth putting some reports in JIRA of the Requires you see missing in ZF's base code. Help contribute to the already good project
gnarf
A: 

You can get rid of these calls in your IDE by replacing "require_once" with "// require_once" require_once should be used only for class loading. Other, for example inserting an array from file like $file = include "test.php";, don't use it (or don't need to use it).

Tomáš Fejfar