Question

This question is related to 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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top