0

How to create or define class in PHP at runtime and defin its attribute and functions? Is it possible?

2
  • 4
    There are probably tons of way to solve your problem without creating classes at the runtime. This is a lot of trouble. Commented Aug 16, 2010 at 4:11
  • 2
    This 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. Commented Aug 16, 2010 at 4:55

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

There is __call and __callStatic magic for overloading methods.
0

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

Well, actually, yes. But it's not recommendable.
0

basically

 class A {
     function B() {...}
 }

everything in php is defined at runtime, so you should be fine with that. You can also try

  include 'some.class.php';

"include" is the same as "eval" but somehow has a better image.

Comments

0

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;
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.