Partial class in PHP like we have in C#

They don't exist.

If, however, you're trying to implement a code generator for which user-land code could be attached (following the same use-case as in C#) then the following may be a viable option:

class Generator
{
    public function generate(Definition $definition)
    {
        if ($this->shouldGenerateTraitFor($definition)) {
            $this->generateTraitFor($definition);
        }
        $this->generateClassFor($definition);
    }
}

Given some implementation like the above, you could then:

(new Generator())->generate(new Definition([
    'class' => 'GeneratedClass', 
    'trait' => 'GeneratedTrait',
]));

And the resulting code may resemble:

class GeneratedClass
{
    use GeneratedTrait;
}

trait GeneratedTrait
{
    // @todo; add "partial" code
}

What is important to note about Generator::shouldGenerateTraitFor is that if it returns false, the trait will not be regenerated. This could be conditional on whether GeneratedTrait.php exists, and is necessary to ensure that when the class is regenerated the hand-written trait code isn't clobbered.

However, it could* be much to your benefit to consider object composition over this approach.

* There are times when I feel that the generated code approach can be cleaner, such as with "entity" types, but that's case-by-case.


PHP uses Traits for this task:

http://php.net/manual/en/language.oop5.traits.php

They allow you to include class parts from an insulated partial file (a Trait) to different classes that shares its logic and maybe other shared logics (like multiple inheritance)

Tags:

C#

Php

Oop