0

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;

}

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.