If you want to get one object from the database, PDO is very useful:
$obj = $handle->fetchAll(PDO::FETCH_CLASS, $obj_name);
If you expect multiple class types to return on the same line (for example: when executing a JOIN), PDO is less useful:
$handle->fetchAll(PDO::FETCH_ASSOC);
... followed by some data matching in the resulting array . Good - except for every method I came up with to achieve this, it looks awful.
My question is : how can I create an instance of several objects from the same array in a graceful, reliable way, when the contents of this array can reflect everything, not a single one, no more than the ones that the classes require?
Example:
, PDO $vars = ('a' => 1, 'b' => 2, 'c' => 3, 'x' => 7, 'y' => 8, 'z' => 9), ABC ( $a, $b $c) XYZ ($x, $y, $z) .
1
class ABC {
private $a, $b, $c;
function __construct ($a = null, $b = null, $c = null) {
$this->$a = $a ? $a : $this->a;
$this->$b = $b ? $b : $this->b;
...
( / /, - )
2
function ABCFactory($vars = array()) {
return new ABC($vars['a'], $vars['b']....
(, , $vars. , isset(), )
3
foreach ($vars AS $key => $value) {
eval("if (isset(\$key) && \$value) \$this->$key = '$value';");
}
( , , , , , ... eval(), !:])
dockeryZ , mleko . , , . :
$def_vars = get_object_vars($this);
foreach ($vars AS $key => $value) {
if (array_key_exists($key, $def_vars)) $this->{$key}=$value;
}
, , Johan Perez ... GET POST!