Home >Database >Mysql Tutorial >How to Dynamically Instantiate PHP Objects Based on Database Types?
Dynamically Instantiating PHP Objects from Database Types
In PHP, it is possible to dynamically create an object based on a string specifying a type defined in a database table. To achieve this, one can utilize the database query and PHP's dynamic object creation capabilities.
Consider a database table with the following columns and sample data:
id | type | propertyVal ----+------+------------- 1 | foo | lorum 2 | bar | ipsum
Suppose we have PHP data types defined as follows:
class ParentClass {...} class Foo extends ParentClass {private $id, $propertyVal; ...} class Bar extends ParentClass {private $id, $propertyVal; ...} // ...(more classes)...
To create an object of a type defined by the database's type column, we can leverage the following steps:
For example:
$result = mysqli_query($conn, "SELECT * FROM table WHERE id = 1"); $row = mysqli_fetch_assoc($result); $type = $row['type']; $instance = new $type; unset($row['type']); foreach ($row as $property => $value) { $instance->$property = $value; }
In this manner, the instance object will be dynamically created with the type specified by the type database column, and its properties will be assigned the values from the selected row.
The above is the detailed content of How to Dynamically Instantiate PHP Objects Based on Database Types?. For more information, please follow other related articles on the PHP Chinese website!