php - PDO::FETCH_CLASS with multiple classes -
i trying turn query result classes.
$result->setfetchmode(pdo::fetch_class, 'myclass', array());
this works quite class name myclass
depends on column values.
is possible fetch each row , turn different class depending on rows values?
user example:
id # name # age 1 # jon # 12 2 # sue # 23 3 # tom # 24
i want have users age less 21 instances of class child
. rows age of 21 , above should instances of class adult
.
so "jon" should instance of child
. "sue" , "tom" should instances of adult
.
as not know type (classname) of returned objects before query, can not specify it.
however, encapsulate logic inside type use return type can return specific return type:
/** * should not have private, public or protected members in it's definition. * * work public properties. */ class returnobject { public function getconcrete() { /* decide here class */ $classname = 'child'; // or 'adult' return $this->selfas($classname); } private function selfas($classname) { $l = strlen(__class__); $s = sprintf('o:%d:"%s"', strlen($classname), $classname).substr(serialize($this), 5+strlen($l)+$l); $instance = unserialize($s); $instance->__construct(); return $instance; } }
you can use getconcrete()
function on each returned object return specific type, decision logic bound database return.
edit: changed version first initialize objects properties via unserialize (please test if works, it's based on assumption we're talking public properties , don't know if pdo setters or more via reflection in mode you're using) , calls constructor function. constructor needs public (and must exist) works.
it's technically possible make available private , protected members well, needs real reflection , needs parsing of serialized data well. class renames classname, not inside private properties.
however 1 way doing so. need ->ischild()
or ->isadult()
function on person
class.
Comments
Post a Comment