I would like to create an object in PHP based on a type defined by a string in a MySQL database. The database table has columns and sample data of:
id | type | propertyVal ----+------+------------- 1 | foo | lorum 2 | bar | ipsum
...with PHP data types
class ParentClass {...} class Foo extends ParentClass {private $id, $propertyVal; ...} class Bar extends ParentClass {private $id, $propertyVal; ...} //...(more classes)...
Using only one query, I would like to SELECT a row by id and create an object of the type define the table's type column with other columns in the SELECTed row being assigned to the newly created object.
I was thinking that using:
mysql_fetch_object()
But know of no way to dynamically create a type based on a string. How does one do this?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With