Consider a web application directory structure as follows.
/index.php
/sub/sub.php
/lib/Class1.php
/lib/Class2.php
where index.php and sub/sub.php are web pages that the user might browse to, and the contents of lib are various class definitions.
So, I'd like to keep all of my class definitions in /lib, or one of its subdirectories, and I'd like to be using these definitions in web pages in various other directory structures on the site. Also, some of these class definitions will reference other class definitions.
The contents of these files would be along these lines.
index.php
<html>
<body>
<?php
$obj2 = new Class2();
$obj2->function2();
?>
</body>
</html>
sub/sub.php - same contents as index.php
<html>
<body>
<?php
$obj2 = new Class2();
$obj2->function2();
?>
</body>
</html>
lib/Class1.php
<?php
class Class1
{
function function1()
{
echo "function1 from Class1";
}
}
?>
lib/Class2.php
<?php
class Class2
{
function function2()
{
$obj1 = new Class1();
$obj1->function1();
echo "function2 from Class2";
}
}
?>
Now, obviously this example won't work as is, since I've not resolved the require/include issues.
I can get things to work if index.php includes
require_once("./lib/Class2.php");
require_once("./lib/Class1.php");
and sub/sub.php includes
require_once("../lib/Class2.php");
require_once("../lib/Class1.php");
but I really don't think it's appropriate for index.php or sub/sub.php to be including/requiring Class1.php when they make no reference to it. (Class1 is used by Class2, which is used by index.php and sub/sub.php.)
I've read that a number of folks like to use a single include.php file that includes everything once. I'm not sure I know how that's supposed to go together. I am sure I don't like the idea of including/requiring everything the web app could possible use (and all of their dependencies) in a single file. That's almost as ugly as including unreferenced dependencies in each file, as demonstrated in the previous paragraph.
My question is, could someone please point out to me how it is that I should be doing this require/include thing?