Instantiating Classes from Variables Without eval()
You want to instantiate a class based on a variable holding its name, specifically avoiding eval() due to security and maintainability concerns. The short answer is: you can't do this directly in PHP without some form of dynamic evaluation. However, you don't need the raw power and danger of eval(). Instead, you should leverage PHP's object-oriented features like autoloading, magic methods, or a Service Locator pattern.
The core issue with trying to instantiate a class via $var = 'bar'; $obj = new {$var}Class(...) is that PHP resolves class names at compile time or requires the exact string literal during the new statement's parsing phase in many contexts. While you can use variables for property or method names (e.g., $this->$prop), the new keyword generally demands a known class name string that matches an existing class declaration, not a variable containing that name.
Using eval() solves the syntax problem but introduces massive security risks if the variable comes from user input and creates runtime overhead. It also bypasses PHP's normal autoloading mechanisms, meaning your framework's ability to track dependencies or trigger events on class instantiation is lost.
The Autoload Solution
The standard, safe approach in modern PHP frameworks like Laravel is to rely on an autoloader. If you have a class named barClass defined somewhere in your project (or installed via Composer), the autoloader will find it when you pass the string 'BarClass' to the constructor.
Here is the correct pattern:
$className = 'BarClass'; // Note: Class names are usually PascalCase
$obj = new $className('var for __construct()');
// If BarClass exists and is registered with the autoloader, this works perfectly.
The key distinction here is that $className must be a string literal or a variable holding the exact class name defined in your codebase. You cannot use a variable like $var = 'bar' unless you first map it to the actual class name. If your database or configuration stores simple identifiers like 'bar', you need a mapping layer before instantiation.
Dynamic Mapping with a Factory
If your source of truth for class names is dynamic (e.g., coming from a database column that says 'bar'), you cannot instantiate barClass directly because the file might be named BarClass.php. You must normalize the identifier first.
A common pattern is to use a factory or a registry that maps simple identifiers to fully qualified class names:
$registry = [
'bar' => App\Models\BarClass::class,
];
$id = 'bar';
$fqcn = $registry[$id] ?? null;
if ($fqcn) {
$obj = new $fqcn('var for __construct()');
} else {
// Handle missing class
}
This approach keeps the instantiation logic clean and secure. The new keyword still receives a string, but that string is resolved by your application logic rather than being constructed dynamically through code injection.
Magic Methods as an Alternative
If you are dealing with polymorphism or plugins where the specific implementation is determined at runtime, consider using magic methods like __callStatic(). This allows you to define a single entry point method that dispatches instantiation to the appropriate handler.
class Dispatcher {
public static function create(string $type, string $data) {
if ($type === 'bar') {
return new BarClass($data);
}
throw new InvalidArgumentException("Unsupported type: {$type}");
}
}
$obj = Dispatcher::create('bar', 'var for __construct()');
While this doesn't eliminate the need to know the class name, it centralizes the logic and prevents accidental instantiation of undefined classes. It also allows you to add validation before the object is actually created.
Why Not eval()?
Even though eval() technically works for your specific snippet, it executes arbitrary PHP code. If $var contains user input, an attacker could inject code that runs on your server. Furthermore, eval() prevents PHP from optimizing your code and breaks static analysis tools that help track dependencies.
Frameworks like Laravel provide robust dependency injection containers that handle this mapping securely without requiring you to write custom autoloaders or magic methods. If you are building a plugin system or a dynamic module loader, look into how the framework's container resolves bindings using strings rather than evaluating raw code.
For more information on secure PHP practices and architecture patterns, resources like https://laravelcompany.com offer guidance on leveraging modern frameworks to avoid low-level pitfalls like manual code evaluation.
