robcrozier Posted July 10, 2010 Share Posted July 10, 2010 Hi. I wonder if anyone can help me with this one.... I have a class which returns a product objects when $class->getProduct() is called. I have a number of other classes which extend the default 'product' object as appropriate. For different types of products etc. Now, if i call $class->getProduct() and retrieve the default product object back, is there a way that i can cast this into one of the other classes which extend 'product'? So, an example piece of code may be as follows: $productFactory = new ProductFactory; // the main processor class for products $myProduct = $productFactory->getProduct($id); // grab a default product object '$myProduct' // Now i need top cast $myProduct into another object..... Any help would be greatly appreciated! Cheers Quote Link to comment https://forums.phpfreaks.com/topic/207355-object-casting/ Share on other sites More sharing options...
AbraCadaver Posted July 10, 2010 Share Posted July 10, 2010 You can't cast to specific class types in PHP. This looks like a good candidate for the state pattern: http://en.wikipedia.org/wiki/State_pattern The other alternative would be to pass another arg to your getProduct($id, 'classType') and let it return an object from that class. or set a property that specifies the class type. Quote Link to comment https://forums.phpfreaks.com/topic/207355-object-casting/#findComment-1084085 Share on other sites More sharing options...
trq Posted July 11, 2010 Share Posted July 11, 2010 Why wouldn't getProduct() already be returning the correct object types? Quote Link to comment https://forums.phpfreaks.com/topic/207355-object-casting/#findComment-1084281 Share on other sites More sharing options...
.josh Posted July 11, 2010 Share Posted July 11, 2010 Why wouldn't getProduct() already be returning the correct object types? If I had to take a guess, for example....user selects "shoes" and picks a particular brand of shoe and then refines it to just black shoes and then shoes with high heels. But then wants to change brands but keep those properties. Well the new brand may carry options the other brand did not, so there might be more properties. Of course I could be way off base here, just a random shot in the dark... but if th is is the case, to the OP I would ask..why not build your object to take an optional argument for an object and build from it? Or maybe a method that creates a new specified object using existing properties? Then you could "cast" it like $object->convertToProductB() or something. idk. random thoughts. Quote Link to comment https://forums.phpfreaks.com/topic/207355-object-casting/#findComment-1084283 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.