Many applications store information about objects in a database. The problem is: how to represent that data in the PHP code? Object-relational mapping (ORM) frameworks can help, but they can be complex and may not always be necessary.
This answer presents a simple solution to dynamically create PHP objects based on strings stored in a MySQL database.
The Problem:
Given a MySQL table with the following schema:
id | type | propertyVal ----+------+------------- 1 | foo | lorum 2 | bar | ipsum
where id is the unique identifier, type is the object type (e.g., foo, bar), and propertyVal is a property value.
The task is to create PHP objects of the dynamic types defined in the type column and populate them with the data from the corresponding row in the table.
The Solution:
In PHP, you can dynamically create an object of a given type using the following syntax:
$type = 'myClass'; $instance = new $type;
Assuming the query returns an associative array, you can assign properties to the object using a similar syntax:
foreach ($row as $property => $value) { $instance->$property = $value; }
Implementation:
Example:
$row = $result->fetch_assoc(); $type = $row['type']; unset($row['type']); $instance = new $type; foreach ($row as $property => $value) { $instance->$property = $value; }
This approach allows you to create dynamic objects from a database without the need for complex ORM frameworks. It's a simple and effective solution for many scenarios where you need to represent database data as dynamic objects in your PHP code.
The above is the detailed content of How to Dynamically Create PHP Objects from MySQL Strings?. For more information, please follow other related articles on the PHP Chinese website!