简体   繁体   中英

Define a class with a variable name in PHP?

I am wanting to be able to do something to the order of this

$name = "Hello".time().mt_rand();
class $name {
    function hellolol() {
        echo "LOL";
    }
}
$name::hellolol();

So that I can build a reload-able module system in PHP. Is this even possible, and if so, how would I go about doing something like this?

EDIT: I've since turned this into a project that essentially does what the accepted answer suggested. Here's a link: https://github.com/Modfwango/Modfwango

$name = "Hello".time().mt_rand();
eval(sprintf('
class %s {
    static function hellolol() {
        echo "LOL";
    }
}', $name));
$name::hellolol();

Pretty nasty but good for mocking, etc.

This technically is possible, just in a very, very bad way.

First, save this file:

<?php
// GeneratedClass.php
class CLASSNAME {
    function hellolol(){
        echo "LOL";
    }
}

Then, use the following to create classes with custom names:

<?php
function generate_class($name){
    eval('?>'.str_replace('CLASSNAME', $name, file_get_contents('GeneratedClass.php')));
}

generate_class("Hello".time().mt_rand());

Again, this is not a good idea! Aside from the fact that anything to do with eval is probably a bad idea, by parsing these classes manually, you'd lose any advantages an IDE would give you, the files wouldn't be cacheable by something like memcached, and it's just altogether a nightmare to use. But it's possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM