Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to create and register class at runtime

Is there any official/recommended way to declare/define/register a new class at runtime in PHP?

What I basically want to do is generating Classes based on the definition stored in a database, both properties and methods.

I have found some article/threads, but all of them are actually old, so I was wondering if it exists some elegant/efficient way to do it. My surprise is that there is no so much information about this as I thought.

Is it so bad? As far as I know, PHP always saves the class definition in memory so I don't see any problem in declaring the class at runtime as it's basically the same result, but maybe I'm wrong.

I think is not relevant right now, but I'm working with Laravel in this project.

Thanks!

like image 660
Desproposito Avatar asked Mar 25 '26 02:03

Desproposito


1 Answers

Yes.

<?php

$foobar = "foobar";

eval("class $foobar {" .
        "function __construct(\$i) {" .
                "echo \"Dark magic ritual complete. \$i virgins sacrificed to satan.\"; " .
        "}" . 
" }");

$evil = new $foobar(5);


echo "<br /><br />";

var_dump($evil);

Produces:

Dark magic ritual complete. 5 virgins sacrificed to satan.

object(foobar)#1 (0) { }

I'm not going to lecture you on semantics, but this is a terribly bad idea and you should reconsider using classes to facilitate what the database records need. A class by itself is not special, but using a class to handle a database entry is perfectly acceptable.

like image 105
Josh Avatar answered Mar 26 '26 14:03

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!