LMSouq
php-dev Open

Creating PHP class instance with a string

JO
Joel
1 month ago
3 views
Problem Description
I have two classes, `class ClassOne { }` and `class ClassTwo {}`. I am getting a string which can be either `"One"` or `"Two"`. Instead of using a long `switch` statement such as: switch ($str) { case "One": return new ClassOne(); case "Two": return new ClassTwo(); } Is there a way I can create an instance using a string, i.e. `new Class("Class" . $str);`?

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base