think123 think123 - 1 year ago 87
PHP Question

How to include two class files at the same time in PHP, so that their methods are accessible between each other?

I have something like the following:

include 'firstclass.php';
include 'secondclass.php';


class First {
public static function foo() {
public static function oof() {
// ...


class Second {
public static function bar() {

As can be seen, I need to access the methods of the
class from the
, and vice versa.

How can I include both so that they are accessible from each other's classes?

Answer Source

You have two options:

Put them in the same file

The easiest quickest fix is to put both classes in the same file. PHP parses the whole file before executing it, so the classes will be able to use each other's methods. This will work, but the more professional and scalable solution is the other option.

Use autoloading

PHP allows you to give it instructions on where to look when you invoke an unknown class. This is called autoloading (intro).

Have an initialization script that runs before all scripts. This is most easily done by setting auto_prepend_file=/path/to/init.php in php.ini (details). Once you've setup such a script, you can add autoloading instructions to it

//function called whenever you use an unknown class. It will
//be passed the name of your class
function my_autoloader($class) {
    include __DIR__ .'/classes/' . $class . '.class.php';


The code above would work if your classes are in a classes subdirectory of init.php, and use the extension .class.php. So to make it work with your example, your directory structure would need to be


Make adjustments to the autoloader as appropriate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download