问题描述
我想基于由 MySQL 数据库中的字符串定义的类型在 PHP 中创建一个对象.数据库表具有以下列和示例数据:
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()
- 读取类型属性
- 创建一个由 type 属性定义的类型的对象
但是不知道基于字符串动态创建类型的方法.如何做到这一点?
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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!