How to create or define class in PHP at runtime and defin its attribute and functions? Is it possible?
-
4There are probably tons of way to solve your problem without creating classes at the runtime. This is a lot of trouble.zneak– zneak2010-08-16 04:11:18 +00:00Commented Aug 16, 2010 at 4:11
-
2This is Pandora's Box. If you find any success in this endeavor, be sure you're ready for the fact that you'll have to track runtime-defined classes and object instantiations of these runtime classes.bcosca– bcosca2010-08-16 04:55:54 +00:00Commented Aug 16, 2010 at 4:55
5 Answers
You could, could, use eval.
But please, don't!
Meta-programming is not something PHP is particularly good at, so you should try to solve your problem without creating classes at runtime.
Comments
you could create a generic extendable class and use the magic __set() and __get() methods to dynamically add properties. no methods though, sorry.
1 Comment
No.
You can however, add properties dynamically to particular instances.
Saying that eval permits this is like saying in Java you could, problematically, write a source file, compile it, and load it (or, for that matter in PHP you could include it). Sure, it's possible, but it's not actually part of the language.
1 Comment
Since PHP7.0 it's possible to use Anonymous classes for it. Example:
$request = new class (
field1: $this->faker->word(),
field2: $this->faker->word(),
field3: $this->faker->word(),
field4: $this->faker->word(),
field5: $this->faker->word(),
) implements RequestInterface {
private string $signature;
public function __construct(
public string $field1,
public string $field2,
public string $field3,
public string $field4,
public string $field5,
) {
}
public function getSignature(): string
{
return $this->signature;
}
public function sign(string $signature): void
{
$this->signature = $signature;
}
};