如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; ...}
//...(更多类)...
使用单一查询(必须先命名包含类名称的字段):
$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);}}
$type = "app\models\MyClass";
- Em.MF