正如Silkfire所说,这可以通过使用PDO特定模式来实现,因此这里是一个示例。 使用相同的数据库值和定义的对象:
id | type | propertyVal
----+------+-------------
1 | foo | lorum
2 | bar | ipsum
class ParentClass {...}
class Foo extends ParentClass {private $id, $propertyVal; ...}
class Bar extends ParentClass {private $id, $propertyVal; ...}
//...(more classes)...
一个查询(您必须先命名包含类名称的字段):
$stmt = $db->prepare('SELECT type,id,propertyVal FROM table WHERE id=1');
$stmt->execute();
$foo = $stmt->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
var_dump($foo); // $foo is a newly created object of class foo, with properties named like and containing the value of subsequent fields
这很酷,但一段时间后会变凉
$stmt = $db->prepare('SELECT type,id,propertyVal FROM table');
$stmt->execute();
while ($object = $stmt->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE))
{var_dump($object);} // here all desired objects, dynamically constructed accordingly to the first column returned by the query
您可以定义一个构造函数(在将数据库中的值分配给属性之后将调用该构造函数)以处理那些动态分配的属性,例如,将字符串替换为其大写的值
class foo
{function __construct ()
{$this->uper = strtoupper($this->propertyVal);}}