Dynamically create PHP object based on string

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;
}

Leave a Comment