Home > Back-end >  How to define a class in php using a variable as class name?
How to define a class in php using a variable as class name?

Time:11-12

I am trying to define multiple classes for via for loop as seen below:

for ($i = 2; $i < 4 ; $i  ) {
            
    $class_name = 'Class_' . $i;        
    
    class $class_name {
    
    public $action;
        
    }
}   

However, the code gives syntax error. How to define classes using variables in php?

CodePudding user response:

This is probably not a good idea, as it can make your code unstable and insecure. However, if you really want to do this you might use eval()

$class_name = 'Class_' . $i;
eval('   
    class ' . $class_name . ' {
    
    public $action;
        
    }
');
  • Related