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;
}
There's a very neat syntax you can use that I learned about a couple of months ago that does not rely on a temporary variable. Here's an example where I use a POST variable to load a specific class:
$eb = new ${!${''} = $_POST['entity'] . 'Binding'}();
In your specific case though, you would be able to solve it by using PDO. It has a fetch mode that allows the first column's value to be the class the row instantiates into.
$sth->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
$instance = new $classname; // i.e. $type in your case
Works very well...
Below is what I was looking for when I came to this thread. use {"objectName"}
(brackets) to declare or reference the object name in the form of a string.
$gameData = new stdClass();
$gameData->location = new stdClass();
$basementstring = "basement";
class tLocation {
public $description;
}
$gameData->location->{'darkHouse'} = new tLocation;
$gameData->location->{"darkHouse"}->description = "You walkinto a dusty old house";
$gameData->location->{$basementstring} = new tLocation;
$gameData->location->{"basement"}->description = "its really damp down here.";
//var_dump($gameData);
echo $gameData->location->basement->description;
This way of referring to the object seems to be interchangeable. I couldn't find the answer so i had to fool around with it Until I found a way.