Dynamically Creating PHP Objects from Strings
Introduction:
In PHP, it is possible to create objects of a specific class dynamically based on a string representation of the desired class name. This technique can be particularly useful in scenarios where the class type is not known in advance or determined programmatically at runtime.
Problem Statement:
Consider a MySQL database where a table stores information about objects, including their type and properties. The task is to create PHP objects of the specified types using a single query and assign the corresponding property values from the same row in the database.
Solution:
To dynamically create PHP objects based on strings in a database, you can follow these steps:
Create the object: Use the following PHP syntax to create an instance of the specified class:
$instance = new $type;
Assign property values: Iterate over the remaining columns in the database row and assign their values to the corresponding properties of the newly created object. For example:
foreach ($row as $key => $value) { if ($key != 'type') { $instance->$key = $value; } }
Example:
Consider the database table mentioned in the problem:
id | type | propertyVal |
---|---|---|
1 | foo | lorum |
2 | bar | ipsum |
Using the solution outlined above, the following PHP code could be used to create objects:
$row = fetchRowFromDatabase(); $type = $row['type']; $instance = new $type; foreach ($row as $key => $value) { if ($key != 'type') { $instance->$key = $value; } }
This code would create an instance of the 'foo' or 'bar' class based on the value in the 'type' column and assign the 'propertyVal' value to the corresponding property of the object.
以上がデータベース内の文字列から PHP オブジェクトを動的に作成するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。