Dynamically Creating PHP Objects from Database Strings
Loading a row from MySQL and instantiating a corresponding class based on a type column is a common pattern in legacy applications or dynamic content management systems. The goal is straightforward: execute a single query, read the data, and return an object of the specific class defined by that string. While intuitive, implementing this safely requires bypassing standard static instantiation methods to handle dynamic class names.
The most direct approach involves using new in conjunction with variable dereferencing or call_user_func. If your environment allows it (PHP 5.3+), you can use the arrow operator to dynamically instantiate a class:
$row = DB::select('SELECT * FROM table WHERE id = ?', [$id]);
$type = $row->type; // e.g., 'Foo'
$className = 'App\\Models\\' . ucfirst($type);
// Safely instantiate the class
$instance = new $className();
This method assumes that the class App\Models\Foo exists and extends a common base. You then map the database columns (propertyVal, id) to the object's properties using setter methods or direct property assignment, provided those properties are accessible (public or protected) and not private.
The Security Implication of Dynamic Instantiation
The primary pitfall here is security. If the type column in your database can be modified by a user without strict validation, you open the door to arbitrary code execution. An attacker could inject a string like 'eval' or 'exec'. If your system blindly constructs the class name and instantiates it, they could run server-side code.
You must whitelist valid types. Never trust the input from the database directly for class name construction unless that data is immutable (e.g., part of the schema definition). Define an array of allowed types:
$allowedTypes = ['Foo', 'Bar', 'Baz'];
if (!in_array($type, $allowedTypes)) {
throw new InvalidArgumentException("Invalid type specified.");
}
Handling Property Mapping
Simply creating the object does not automatically populate its properties from the database row. In your schema, you likely have classes like:
class Foo extends ParentClass {
private $id;
private $propertyVal;
// Constructor or setter needed to assign data
}
To assign data dynamically, you have a few options. The most robust is defining a constructor in your base class that accepts an array and maps values to properties using reflection or explicit setters. Using Reflection allows you to bypass the private modifier temporarily if necessary:
$className = 'App\\Models\\' . ucfirst($type);
$instance = new $className();
$reflection = new ReflectionClass($instance);
foreach ($row->toArray() as $key => $value) {
// Check if a setter exists first, otherwise try direct property access
$setter = 'set' . ucfirst($key);
if (method_exists($instance, $setter)) {
$instance->$setter($value);
} else {
try {
// Fallback for public/protected properties
$property = $reflection->getProperty($key);
$property->setAccessible(true);
$property->setValue($instance, $value);
} catch (ReflectionException $e) {
// Handle property not found or private without setter
}
}
}
Why mysql_fetch_object Isn't Enough
You might recall that older PHP functions like mysql_fetch_object() could return an object directly based on a class name if provided. However, this function is deprecated and removed in modern PHP versions (PostgreSQL, SQLite, and MySQLi drivers do not support this behavior in the same way). Relying on legacy database extension quirks is no longer a viable strategy for new development.
If you are working within the Laravel ecosystem, consider using Eloquent's polymorphic relationships or a dedicated factory pattern to handle type resolution outside of the database layer. This keeps your database schema simple while allowing your application logic to enforce strict type boundaries.
For more details on handling dynamic data structures in PHP applications, see https://laravelcompany.com.