Jump to content

Object casting


robcrozier

Recommended Posts

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

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.