Home > Database > Mysql Tutorial > How to Dynamically Instantiate PHP Objects Based on Database Types?

How to Dynamically Instantiate PHP Objects Based on Database Types?

Susan Sarandon
Release: 2024-11-24 15:19:11
Original
693 people have browsed it

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
Copy after login

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)...
Copy after login

To create an object of a type defined by the database's type column, we can leverage the following steps:

  • Execute a query that selects a row with the desired id.
  • Use mysql_fetch_object() to retrieve the data as an associative array.
  • Obtain the type value from the associative array.
  • Dynamically create an object of that type using the syntax: $instance = new $type;.
  • Assign the remaining properties of the object from the associative array.

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template