简体   繁体   English

在PHP中用变量名定义一个类?

[英]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. 这样我就可以用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 这是链接: 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. 除了与eval有关的事情可能不是一个好主意之外,通过手动解析这些类,您将失去IDE会给您带来的任何优势,这些文件将无法被诸如memcached之类的内容缓存,并且完全是这样一场噩梦。 But it's possible. 但这是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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