How to split a PHP class to separate files?

If your only goal is to make the class definition file smaller, you can include files within a function definition

class MyClass {
    public function doStuff($foo,$bar) {
        global $quz;
        include('MyClass.doStuff.php');
    }
}

Within the include, your local scope applies ($foo,$bar and $quz will be defined)

I'm not sure what the overhead is - the include seems to happen at run-time, not compile time (since an include can actually return a value ..)


a-priori PHP doest not give you this feature by language construction, the whole class must be in a single file.

Now there are tricks that could do the stuff, but they are quite heavy CPU demanding:

You can for example dissociate your classes between different files, then load the files and build a single string with the whole code, then do an eval(string) to interprete the classes and build them into the runnable code area.

not really a good idea btw for many reasons


As of PHP 5.4, you can accomplish this with Traits. To quote the official documentation:

Traits [enable] a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. [...] A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Using a trait allows you to store helper methods that address cross-cutting concerns in a central place and use these methods in whatever classes you need.

// File "HelperMethodTrait.php"
trait HelperMethodTrait
{
    public function myIncredibleUsefulHelperFunction()
    {
        return 42;
    }
}

// File "MyClass.php"
class MyClass
{
    use HelperMethodTrait;

    public function myDomainSpecificFunction()
    {
        return "foobar";
    }
}

$instance = new MyClass();
$instance->myIncredibleUsefulHelperFunction(); // 42

Tags:

Php

Class