0

I would like to create a php class by a variable name something like

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

I want an answer without using no eval.

7
  • If you give us some insight into why you would need this, we might be able to help you better. What problem are you trying to solve? Commented Sep 20, 2017 at 0:16
  • I was creating custom mvc framework and am trying to create a class by a filename. Commented Sep 20, 2017 at 0:29
  • Why would you need to "create a class by a filename" and what does that actually mean? I've used plenty of MVC frameworks (including the ones I've built my self) and have never seen or needed this. Can you give some concrete example? Commented Sep 20, 2017 at 0:32
  • Let's say i am building user interface for it and i need to create classes by user inputs which are only associated with that user. Let alone creating am not even able to extend classes by variables. Commented Sep 20, 2017 at 0:37
  • That didn't really make it clearer. I mean, you would still need to define the properties and methods for the classes (since it otherwise would be kind of pointless), so why not just create a new instance of some already-defined class? Commented Sep 20, 2017 at 0:40

1 Answer 1

2

If you need to dynamically define classes, then use Anonymous Classes, otherwise you should be giving your classes fixed names, not based on random variable values

$class = new class() {
    function function_one() {
        echo "LOL";
    }
};

$class->function_one();

But why do you need to use dynamically defined classes like this?

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

6 Comments

Great answer to a rather strange request. To add a little to it, he might even get his naming scheme working using variable variables, $time = time(); $class{$time} = new class() {
I was creating custom MVC frame works and am trying to avoid extending classes.
The code isn't working Parse error: syntax error, unexpected 'class' (T_CLASS) in
@iamnamrud What PHP-version are you using? Anonymous classes was introduced in PHP 7.
Thanks i just find out now am updating. I hope anything wouldn't mess when i update. Are there any depreciated PHP builtins?
|

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.