基于字符串动态创建PHP对象 [英] Dynamically create PHP object based on string
问题描述
我想在PHP中根据MySQL数据库中的字符串定义的类型创建一个对象。数据库表具有列和样本数据:
I would like to create an object in PHP based on a type defined by a string in a MySQL database. The database table has columns and sample data of:
id | type | propertyVal
----+------+-------------
1 | foo | lorum
2 | bar | ipsum
... PHP数据类型
...with PHP data types
class ParentClass {...}
class Foo extends ParentClass {private $id, $propertyVal; ...}
class Bar extends ParentClass {private $id, $propertyVal; ...}
//...(more classes)...
只有一个查询,我想通过id选择一个行,并创建一个类型的对象定义表的类型列与SELECTed行中的其他列分配给新创建的对象。
Using only one query, I would like to SELECT a row by id and create an object of the type define the table's type column with other columns in the SELECTed row being assigned to the newly created object.
我在想:使用:
-
mysql_fetch_object()
- 读取类型属性
- 创建类型属性定义的类型的对象
但是知道没有办法动态创建一个基于字符串的类型。如何做到这一点?
But know of no way to dynamically create a type based on a string. How does one do this?
推荐答案
但是知道没有办法基于字符串动态创建类型。如何做到这一点?
But know of no way to dynamically create a type based on a string. How does one do this?
您可以轻松自然地进行:
You can do it quite easily and naturally:
$type = 'myclass';
$instance = new $type;
如果您的查询返回关联数组,可以使用类似的语法指定属性:
If your query is returning an associative array, you can assign properties using similar syntax:
// build object
$type = $row['type'];
$instance = new $type;
// remove 'type' so we don't set $instance->type = 'foo' or 'bar'
unset($row['type']);
// assign properties
foreach ($row as $property => $value) {
$instance->$property = $value;
}
这篇关于基于字符串动态创建PHP对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!