views:

115

answers:

2

This question is related to http://stackoverflow.com/questions/1721949/downcasting-in-php5

How expensive is this php downcasting workaround?

Is this php downcasting workaround too expensive?

I've echoed microtimes and It seems that it takes like 0.001. I wonder if It could be a problem in a large foreach.

public static function to($obj) {

 return unserialize(preg_replace(
 '/^O:\d+:\"(\w+)/',
 'O:' . strlen('this_class_name') . ':"' . 'this_class_name',
 serialize($obj)));
}

Solutions proposed in http://php.net/manual/en/language.types.type-juggling.php comments are similar.

+2  A: 

By presenting the time 0.001 (seconds, I presume), you appear to have answered your own question about how expensive the operation is.

As to whether that is too expensive, I'd say that is best answered by comparing it to the alternatives.

One alternative, from the answer to your other SO question, is to construct a new object. You will have to experiment to see if that approach is quicker.

Your snippet seems cumbersome, and it appears to be from "toma at smartsemantics dot com" at the PHP page. I'm trying to figure out what your $obj might be, and a little context about your problem, to see if there are any alternatives that don't involve downcasting.

Probably, downcasting is intentionally prohibited in PHP to dissuade people from using downcasting. That is because an OOP design that requires it is flawed according to the Liskov substitution principle.

Ewan Todd
The problem is the following. Figure out I have autogenerated models (Zend_Model_X) from a database. I have child classes from those models where I put extra methods. The problem is that If I use fetchList what I get is a Zend_Model_X list, so those custom methods are not avaiable. The typical Java solution is downcasting. Another solution would be using a fetchListArray method but I would really prefer a array of objects.And yep, that code is not mine. I want a way to make a copy from the object with generic code. This way I could script the generation of this downcasting method.
ktulur
+2  A: 

I really don't think you should be concerned with how expensive this is, rather concern yourself with the fact that you're trying to implement high level functionality into a programming language at the application level. This just seems like a very bad idea.

If downcasting is that needed within your web application, maybe PHP is not the best choice for it. I however seriously doubt that downcasting is really needed, with better design you can avoid using it all together.

evolve