tags:

views:

38

answers:

2

I have an abstract parent class Item, from which different types of items extend: ItemTypeA, ItemTypeB, and ItemTypeC. From my database result, I have an array:

array(

'item_name' => 'This is the item name',
'item_type' => 'ItemTypeA'

);

In PHP, what's the best way to create the item? Should I do something similar to the following?

static function constructFromDatabase($result){

$type = $result['item_type'];
$item = new $type;
return $item;

}
+1  A: 

Yes, $item = new $type; should work just fine, source

jigfox
A: 

You can even do return new $result['item_type'];, for performance -and maybe clarity/simplicity- reasons, if you are not going to use the intermediate variables anywhere else.

battal