0

I use PDOStatement object to fetch result of a query into an object of NewOrder class type.

$result = $pdo->query($strsql);
$result->setFetchMode(PDO::FETCH_CLASS, 'NewOrder');
$order = $result->fetch()

NewOrder is a base class that has children. I always need to instantiate a child rather than this base class NewOrder (it could be an abstract class but then the fetching wouldn't work). However, which child to instantiate can be determined based on value in order_type field of the result. After the result is fetched I have access to this value:

$orderType = $order->getOrderType();

Once I get this value, is it possible to change the type of $order object from NewOrder to one of its children (depending on the value $orderType)? The reason why I want to do it this way is because I want to avoid creating a new object and reassigning all attributes from object $order of NewOrder type to object $order2 of NewOrderChild type.

user2395238
  • 850
  • 1
  • 9
  • 20

1 Answers1

0

You cannot typecast objects in PHP. See answer for Type casting for user defined objects.

Maybe you want to have a look at Doctrine 2 ORM which supports this type of mapping through Single Table Inheritance.

Community
  • 1
  • 1
mhall
  • 3,671
  • 3
  • 23
  • 35