Clay Freeman
Clay Freeman

Reputation: 543

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

Upvotes: 0

Views: 1560

Answers (2)

Adam
Adam

Reputation: 2889

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.

Upvotes: 3

chelmertz
chelmertz

Reputation: 20601

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

Pretty nasty but good for mocking, etc.

Upvotes: 4

Related Questions