• (cs)

    PHP. TRWTF.

  • (cs) in reply to Dogsworth

    Transformation between (relevant) types by serialization and deserialization is actually quite common and useful. In fact many mainstream, well-designed systems rely on exactly this mechanism...

  • justsomedudette (unregistered)

    Can someone explain that one please

  • alex (unregistered) in reply to justsomedudette

    The serialize function transforms any variable (including objects) into a string representation. This string may be unserialized to obtain the same variable/object again.

    O:7:"MyClass":0:{}

    When serializing an object, the name of the class becomes part of the serialized string. So if you serialize, str_replace() the class name and then unserialize... VOILA! you get an object of a different type!!

  • (cs)

    it's not a wtf in itself, much more the symptom of a deeper, much worst wtf somewhere in the code base and a demented coder in the office.

  • (cs)

    I feel sick.

    A truly 'golden' WTF. Thanks, I guess?

  • Renoir (unregistered)

    my eyes! they hurt!

    this is wrong on so many levels....

  • 50% Opacity (unregistered)

    Please don't blame this on PHP. Stupid coders do stupid shit in any language. -_-;;

  • anonymous_coder() (unregistered)

    Well, that's the most unholy bit of coding I've seen on this site in a long, long time. I mean, I know the OO capabilities of PHP are lacking compared to most other languages, but this... I mean, damn.

    It's the combination of technical proficiency needed to even make that work and complete lack of understanding at how messed up this will be for maintenance coding this will be that takes the cake.

  • 3zhrea2 (unregistered)

    That just shows what a hack PHP is.

    Real languages have a defined API, and make that much easier.

  • My name (unregistered)

    Well, real type conversion is only for real programmers using real programming languages...

  • (cs)

    Funny... He could have just returned the unserialized object instead of molesting the input.

  • Franky (unregistered)

    I don't get at all what this might be useful for ...

  • (cs) in reply to anonymous_coder()

    I really wonder what happens when you try this with incompatible classes. Presumably the deserializer will block such operations, but then again, it is generally best not to presume too much with PHP.

  • (cs) in reply to FragFrog
    FragFrog:
    I really wonder what happens when you try this with incompatible classes. Presumably the deserializer will block such operations, but then again, it is generally best not to presume too much with PHP.

    Don't worry, it does exactly what you expect from PHP:

    <?php
    
    class A {
      private $a = 'a';
    }
    
    class B {
      private $b = 'b';
    }
    
    function changeClass(&$object,$newClassName) {
      if (class_exists($newClassName,false)) {
        $object = unserialize(preg_replace("/^O:[0-9]+:\"[^\"]+\":/i", "O:" . strlen($newClassName) . ":\"" .$newClassName."\":", serialize($object)));
      }
    }
    
    $aa = new A();
    
    echo "\n\noldObject:\n";
    var_export($aa);
    
    changeClass($aa,'B');
    
    echo "\n\nnewObject:\n";
    var_export($aa);
    </pre>
    

    Returns:

    oldObject:
    A::__set_state(array(
       'a' => 'a',
    ))
    
    newObject:
    B::__set_state(array(
       'b' => 'b',
       'a' => 'a',
    ))
    

    No warnings or similar of course.

  • (cs)

    This code has made me literally feel ill.

    I always thought when people say that it was just hyperbole, but it turns out that it is actually possible to feel sick just from looking at egregiously awful code.

  • Geoff (unregistered) in reply to TheCPUWizard

    Wells yes but usually you do a little more than applying a regex to the string that tells the interpreter what type of object its going to unserialize. That and they objects/types need to be compatible, I assume that is what you mean by 'relevant'.

    This code would be perfectly happy to try and turn a duck into a car. It would be nice if it had duck-type style checks or something in it that would produce a useful error if you try and transmogrify something that won't work. I would guess there was a need transform between two very specific types that lead to this 'solution' and it would be nice if the code checked that it really was getting them as input and raised an understandable exception when something else is passed.

    Good luck to whoever gets to maintain this codebase.

  • Chris Chilvers (unregistered)

    Of course, smalltalk had this feature years ago with become http://gbracha.blogspot.co.uk/2009/07/miracle-of-become.html while open to abuse, it can also allow for some interesting solutions to things like the state pattern.

  • Kuli (unregistered) in reply to Chris Chilvers
    Chris Chilvers:
    Of course, smalltalk had this feature years ago with become http://gbracha.blogspot.co.uk/2009/07/miracle-of-become.html while open to abuse, it can also allow for some interesting solutions to things like the state pattern.

    Yes, and in Smalltalk you can change the class of every object easily with #changeClassToThatOf:

    http://www.cincomsmalltalk.com/userblogs/mls/blogComments?entry=3315628761

  • (cs) in reply to Geoff
    Geoff:
    ...This code would be perfectly happy to try and turn a duck into a car.

    Maybe that's the trick to get a floating car:-)

  • Vb (unregistered)

    Ths can be useful in certain cases. For example, when working with web services, the PHP implementation will return a generic object for you with all the fields of the class that you were trying to get but none of the methods as PHP doesn't know what class the object should be. If you want to actually convert the object into an instance of that class to be able to call methods of that class, you would need to do a hack like this.

  • (cs) in reply to Vb
    Vb:
    Ths can be useful in certain cases. For example, when working with web services, the PHP implementation will return a generic object for you with all the fields of the class that you were trying to get but none of the methods as PHP doesn't know what class the object should be. If you want to actually convert the object into an instance of that class to be able to call methods of that class, you would need to do a hack like this.

    Or you can use reflection. Even PHP has reflection support.

  • Aaron Rowe (unregistered)

    Looks like a smart answer to the wrong problem!

  • (cs)

    Why do people blame bad programming in a language, for example PHP, on the language itsself? Do we also blame bad grammar use on English?

  • (cs)

    Ok, let me see if I got this right... is he shoehorning a new type to existing data by replacing its class name?

    Evil. In its purest form.

    BTW... Brad, can you post his Linked In profile? ...just curiosity...

  • (cs) in reply to Dogsworth
    Dogsworth:
    PHP. TRWTF.

    I hear a lot how this or that language is bad. Could somebody give me a list of languages which are good?

  • gizmore (unregistered)

    We can easily improve the function and allow arbitrary classnames. Also i added a boolean to control if we should try to include classes beforehand.

    public static function changeClass(&$object,$newClassName, $boolTryToLoadClasses) { if (!class_exists($newClassName,$boolTryToLoadClasses)) { eval "class {$newClassName} {}"; } $object = unserialize(preg_replace("/^O:[0-9]+:"[^"]+":/i", "O:" . strlen($newClassName) . ":"" .$newClassName."":", serialize($object)));

    } Although it does not shuffle, i have adapted the function into the gizmore framework ;)

    Consequat: This word is self explaining.

  • nom (unregistered)

    So verbose and awkward. In Python it's just:

    foo.__class__ = otherClass

    (not that you should actually do that unless you have a damn good reason)

  • nom (unregistered) in reply to Shoreline
    Shoreline:
    Dogsworth:
    PHP. TRWTF.

    I hear a lot how this or that language is bad. Could somebody give me a list of languages which are good?

    "There are only two kinds of languages: the ones people complain about and the ones nobody uses." - Bjarne Stroustrup

  • (cs) in reply to TheCPUWizard
    TheCPUWizard:
    Transformation between (relevant) types by serialization and deserialization is actually quite common and useful. In fact many mainstream, well-designed systems rely on exactly this mechanism...
    Useful - well maybe if you're lazy, prepared to rely on bodges and side effects and performance isn't an issue.

    Common - You're having a fucking laugh aren't you?

  • Mike (unregistered) in reply to Geoff

    Couldn't you pretty much do this in any language though? Say C# you serialize an object. Then create a deserializer and pass it a type that looks just the same serialized as the other except with different methods. The real WTF would be if PHP doesn't have any other method to case objects (which might be the case I don't know never played with it) but I mean you are expressing your intent to convert from one type to another albeit indirectly. If you don't like what you get than that is your fault.

  • Not an english native (unregistered) in reply to Sitethief
    Sitethief:
    Why do people blame bad programming in a language, for example PHP, on the language itsself? Do we also blame bad grammar use on English?

    Well...

  • Smug Unix User (unregistered)

    I think it should have been named blind duck.

  • Fred (unregistered)

    If you're too lazy to setf:

    (defmacro coercef (object new-class-name)
      `(setf ,object (coerce ,object ,new-class-name))) ; Done!
    

    Use case:

    (let ((obj '(a b c)))
      (print obj)
      (coercef obj 'vector)
      (print obj))
    

    Output:

    (A B C) 
    #(A B C)
    

    Returns final value of obj:

    #(A B C)
    

    shudders

  • nom (unregistered) in reply to Sitethief
    Sitethief:
    Why do people blame bad programming in a language, for example PHP, on the language itsself? Do we also blame bad grammar use on English?

    Sure, why not? English has a very complicated grammar and no consistent set of pronunciation rules. It's basically a hodgepodge of features stolen from other languages, hastily grafted together with little thought to consistency, that is widely used due to familiarity and network effects.

    That's how languages work.

  • PotOGold (unregistered)

    I had to do this in Java when the names of XML exported classes had to be changed (including the package name). This was required to provide for backward compatibility. Usually, backward compat is less hard to do - the deserializer just hast to have access to stub methods providing the old interface, but once the name of a class has to change (because code would be really ugly otherwise or the old class structure was a WTF - as was the case in my example) it might become dirty. So: This might be a WTF, but it might also be the right solution for certain use-cases. Just because you never came across it yourself does not make it a WTF.

  • PotOGold (unregistered) in reply to PotOGold
    PotOGold:
    Just because you never came across it yourself does not make it a WTF.

    Which, BTW, holds for many of the articles at TDWTF.

  • 3zhrea2 (unregistered) in reply to nom
    Sure, why not? English has a very complicated grammar and no consistent set of pronunciation rules. It's basically a hodgepodge of features stolen from other languages, hastily grafted together with little thought to consistency, that is widely used due to familiarity and network effects.

    So, just like PHP, eh?

  • Anon (unregistered) in reply to 50% Opacity
    50% Opacity:
    Please don't blame this on PHP. Stupid coders do stupid shit in any language. -_-;;

    True enough, but PHP is the single most efficient productivity tool ever devised for the writing of shitty code. (An honorable mention goes to VB, of course).

  • void* (unregistered)

    In C, C++, C#, Java, etc. (even SQL) you can just use a cast to change the type. Much simpler.

  • röb (unregistered)

    I guess cloning the object was out of the question... There can't be any actual use for this ever or maybe I just lack the imagination that this dev had... It probably opens a portal to Cthulhu's beach house in the Hamptons.

  • (cs) in reply to Shoreline
    Shoreline:
    Dogsworth:
    PHP. TRWTF.

    I hear a lot how this or that language is bad. Could somebody give me a list of languages which are good?

    I'd suggest you start by defining "good" in the context of languages.

  • ¯\(°_o)/¯ I DUNNO LOL (unregistered) in reply to sztupy
    sztupy:
    oldObject: A::__set_state(array(   'a' => 'a', ))

    newObject: B::__set_state(array(   'b' => 'b',   'a' => 'a', ))

    (obligatory) Once upon a time, a programmer had a problem. So he decided to use a regex. Then he had two problems.

  • (cs) in reply to Shoreline
    Shoreline:
    Dogsworth:
    PHP. TRWTF.

    I hear a lot how this or that language is bad. Could somebody give me a list of languages which are good?

    ERROR: NO RECORDS FOUND.

  • jbarop (unregistered)
  • 50% Opacity (unregistered) in reply to nom
    nom:
    Sure, why not? English has a very complicated grammar

    I'd disagree. English grammar is one of the simpler ones. It may have a couple of rough edge cases, but mostly English grammar is dead simple.

    nom:
    and no consistent set of pronunciation rules.

    The pronunciation of words varies from place to place, but this is the case with any language that is spoken among geographically divers people which do not all communicate each and every day with each other. English suffers from this a lot since it's probably the most geographically diverse language to date. Since there's only one, no, sorry, two spelling systems, you're bound to come across inconsistencies.

    nom:
    It's basically a hodgepodge of features stolen from other languages, hastily grafted together with little thought to consistency, that is widely used due to familiarity and network effects.

    Name one natural language that does not fit this definition.

    I find English pretty convenient due to its very rich vocabulary and very flexible grammar rules. Compared to the two other languages I speak (Japanese and German), it's mighty simple. Japanese can compete with it in terms of flexible and simple grammar, but ease of use and expressiveness is very high up there in English.

  • iWantToKeepAnon (unregistered) in reply to Dogsworth
    Dogsworth:
    PHP. TRWTF.

    "{Your technology I don't like}. TRWTF." .... is TRWTF. Please have something to add when you comment.

    Worst ... comment ... ever. Thank you.

  • (cs)

    So this is what the PHP equivalent of C++’s reinterpret_cast<> looks like.

  • Sir Bedevere (unregistered) in reply to Geoff
    Geoff:
    This code would be perfectly happy to try and turn a duck into a car. It would be nice if it had duck-type style checks or something in it that would produce a useful error if you try and transmogrify something that won't work.

    For instance, it only works if duck.weight == car.weight, and CanBuildBridge(duck) returns true.

  • Kuli (unregistered) in reply to void*
    void*:
    In C, C++, C#, Java, etc. (even SQL) you can just use a cast to change the type. Much simpler.

    Wow! Well, ...

    no.

Leave a comment on “Pot o' Gold”

Log In or post as a guest

Replying to comment #410550:

« Return to Article