Is there any simple way to have a concept of partial class in PHP like we have in C#? I've tried to make it possible using different namespace but it couldn't work.
Partial class is a single class defined in multiple files. Trait: definitions that can be used in different classes.
There can be zero or more partial class definitions for every full definition of a class. Every partial class definition of a class must lexically precede the one full definition of that class, but doesn't have to precede forward declarations of the class.
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.
partial classes can work by convention. For example consider this convention. // file main function SomeObject() { for (var i = 0, ii = SomeObject. Partial.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With