"PHP has an eval function like perl"

« Return to Article
  • FragFrog 2009-10-26 09:12
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.

    A LOT of crap gets written in PHP because people don't know what they are doing, but to write truely good PHP code is both possible as well as just as hard as writing good code in any other language. It's just that PHP makes writing bad code so much easier :]

  • EatenByAGrue 2009-10-26 09:14
    The real question is whether Jim's reporting application generated paper reports that could be faxed to the head office, placed on a wooden table, photographed, and the photograph emailed out.
  • EmperorOfCanada 2009-10-26 09:20
    Maybe he had tonnes of Lisp/AI experience and was planning on building a self coding dynamic intelligent system?
    Or maybe he was a dumbass.
  • Nano 2009-10-26 09:22
    Fragfrog: eval != variable expansion
  • ZanderZ 2009-10-26 09:24
    QFT.
    Code like this gives me physical pain. Luckily I don't have a job as programmer so I don't have to maintain other peoples code :)
  • ZanderZ 2009-10-26 09:24
    FragFrog:
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.

    A LOT of crap gets written in PHP because people don't know what they are doing, but to write truely good PHP code is both possible as well as just as hard as writing good code in any other language. It's just that PHP makes writing bad code so much easier :]


    QFT.
    Code like this gives me physical pain. Luckily I don't have a job as programmer so I don't have to maintain other peoples code :)

    (Damnit, forgot to quote the message in my previous post)
  • highphilosopher 2009-10-26 09:34
    Unfortunately it's people like this that give PHP a bad name. There's nothing wrong with PHP, just something wrong with learning any language in 21 days.
  • Jim Lard 2009-10-26 09:37
    Why does Jim need both "hostid" and "hostname" in his key anyway? Are there multiple servers with the same "hostid" but different "hostname"? I guess that's possible - if a machine is being dual-booted for multiple purposes for example. But are there also multiple servers with the same "hostname" but different "hostid"? That seems rather less likely.
  • noway! 2009-10-26 09:41
    FragFrog:
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.

    That's variable expansion, not code evaluation. Although, i think the quotes are redundant... right?
  • Myname! 2009-10-26 09:41
    The suggested code is a WTF in itself. If the value doesn't exist, then there's no need to set the result to "null" because it's already the type NULL which would turn into "null" at any string conversion. If the value was an empty string as the bad code suggested then isset() would return true and it'll stay as "".
  • Book title 2009-10-26 09:43
    "Learn PHP in 21 hours"

    FTFY.
  • Myname! 2009-10-26 09:45
    Myname!:
    The suggested code is a WTF in itself. If the value doesn't exist, then there's no need to set the result to "null" because it's already the type NULL which would turn into "null" at any string conversion. If the value was an empty string as the bad code suggested then isset() would return true and it'll stay as "".


    Actually, scratch that, just realised what the code was actually doing. Where's my coffee...
  • Schmalls 2009-10-26 09:51
    noway!:
    FragFrog:
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.

    That's variable expansion, not code evaluation. Although, i think the quotes are redundant... right?


    No the quotes aren't redundant. It is doing the same thing as:
    $x[hostid] . '.' . $x[hostname]
    However, a big WTF is that the array key isn't quoted like so:
    $x['hostid'] . '.' . $x['hostname']
    When left unquoted, PHP first checks to see if there are constants named hostid and hostname and if there are none it emits a notice and uses the string instead.
  • The_Assimilator 2009-10-26 09:54
    Jim aggressively fought off all attempts at transitioning the application the development team so, during a round of cost cutting, Jim was made redundant.


    PHP Parse error: parse error: supplied sentence does not contain valid grammar in C:\Inetpub\wwwroot\tdwtf\Articles\PHP-has-an-eval-function-like-perl.aspx on line 5
  • Anon Ymous 2009-10-26 10:07
    The_Assimilator:
    Jim aggressively fought off all attempts at transitioning the application the development team so, during a round of cost cutting, Jim was made redundant.


    PHP Parse error: parse error: supplied sentence does not contain valid grammar in C:\Inetpub\wwwroot\tdwtf\Articles\PHP-has-an-eval-function-like-perl.aspx on line 5


    There's nothing wrong with the grammar of that sentence. "Fight off" is a phrasal verb -- it has a different meaning than "fight". (Or are you whining about the use of the passive voice?)
  • Kermos 2009-10-26 10:11
    Dunno if I can really say WTF here. The story itself clearly states this guy had absolutely no programming background and apparently, when he first wrote this application, I it doesn't appear there were any developers available to hand the task off to.

    Given that the developer team later on didn't completely scrap the entire code base and was able to refactor it to me indicates that overall, it couldn't have been *that* bad. I think primarily the project just grew to a size where this guy could no longer handle it with his limited experience.

    I think we all can agree that every one of us has produced WTF Worthy code when we first started writing software.

    Had this guy been someone claiming to be the greatest programmer of all time with a 6 digit salary, then yes, I'd definitely say WTF. But seeing how the story clearly states he was a beginner, I'd say rather than pointing at him and screaming WTF, someone should maybe consider giving a person like that some pointers in how to do things better. Never know, might actually get a great developer out of it eventually...

  • Robo 2009-10-26 10:15
    "transitioning the application the development team"?
  • Alex 2009-10-26 10:20
    Pedantic exception in PHP Parse error: parse error:

    Supplied sentence does contain valid grammar, it does however contain invalid grammar as well.

    Lol
  • Jim 2009-10-26 10:20
    Now that I am redundant, I would just like to say that it's no fun being redundant.
  • MyKey_ 2009-10-26 10:21
    Kermos:
    Dunno if I can really say WTF here. The story itself clearly states this guy had absolutely no programming background and apparently, when he first wrote this application, I it doesn't appear there were any developers available to hand the task off to.

    Given that the developer team later on didn't completely scrap the entire code base and was able to refactor it to me indicates that overall, it couldn't have been *that* bad. I think primarily the project just grew to a size where this guy could no longer handle it with his limited experience.

    I think we all can agree that every one of us has produced WTF Worthy code when we first started writing software.

    Had this guy been someone claiming to be the greatest programmer of all time with a 6 digit salary, then yes, I'd definitely say WTF. But seeing how the story clearly states he was a beginner, I'd say rather than pointing at him and screaming WTF, someone should maybe consider giving a person like that some pointers in how to do things better. Never know, might actually get a great developer out of it eventually...



    Agreed! But giving pointers to a newbie is a very, very bad idea. Hints are better!

    [UPDATE: Sorry, I forgot the mandatory http://xkcd.com/138/.]
  • mbvlist 2009-10-26 10:28
    Schmalls:


    No the quotes aren't redundant. It is doing the same thing as:
    $x[hostid] . '.' . $x[hostname]
    However, a big WTF is that the array key isn't quoted like so:
    $x['hostid'] . '.' . $x['hostname']
    When left unquoted, PHP first checks to see if there are constants named hostid and hostname and if there are none it emits a notice and uses the string instead.

    It doesn't work like that when in a string AFAIK. You can test it using this code:
    $array['true'] = 'The Real WTF is PHP syntax.';
    $var1 = "$array[true]";
    $var2 = $array['true'];

    I think $var1 and $var2 have the same value. Don't ask me why, it is pretty much crap anyway.
  • sao 2009-10-26 10:29
    MyKey_:
    Kermos:
    Dunno if I can really say WTF here. The story itself clearly states this guy had absolutely no programming background and apparently, when he first wrote this application, I it doesn't appear there were any developers available to hand the task off to.

    Given that the developer team later on didn't completely scrap the entire code base and was able to refactor it to me indicates that overall, it couldn't have been *that* bad. I think primarily the project just grew to a size where this guy could no longer handle it with his limited experience.

    I think we all can agree that every one of us has produced WTF Worthy code when we first started writing software.

    Had this guy been someone claiming to be the greatest programmer of all time with a 6 digit salary, then yes, I'd definitely say WTF. But seeing how the story clearly states he was a beginner, I'd say rather than pointing at him and screaming WTF, someone should maybe consider giving a person like that some pointers in how to do things better. Never know, might actually get a great developer out of it eventually...



    Agreed! But giving pointers to a newbie is a very, very bad idea. Hints are better!

    [UPDATE: Sorry, I forgot the mandatory http://xkcd.com/138/.]


    agreed, but only initialized pointers
  • Anonymous 2009-10-26 10:30
    "Personal Home Page". That is all.
  • Severity One 2009-10-26 10:31
    FragFrog:
    ...but to write truely good PHP code is both possible as well as just as hard as writing good code in any other language.

    I would say it's a lot harder. :)
  • anonymous 2009-10-26 10:36
    Anon Ymous:
    The_Assimilator:
    Jim aggressively fought off all attempts at transitioning the application the development team so, during a round of cost cutting, Jim was made redundant.


    PHP Parse error: parse error: supplied sentence does not contain valid grammar in C:\Inetpub\wwwroot\tdwtf\Articles\PHP-has-an-eval-function-like-perl.aspx on line 5


    There's nothing wrong with the grammar of that sentence. "Fight off" is a phrasal verb -- it has a different meaning than "fight". (Or are you whining about the use of the passive voice?)


    The problem is that it should be "at transitioning the application TO the development team".
  • Anonymous 2009-10-26 10:36
    MyKey_:
    [UPDATE: Sorry, I forgot the mandatory http://xkcd.com/138/.]

    XKCD currently has the best Geocities commemoration I've ever seen - complete with blink tags, broken images and malformed HTML aplenty. It looks exactly like any Geocities page of the nineties. Good times.
  • Lee K-T 2009-10-26 10:39
    FragFrog:

    A LOT of crap gets written in PHP because people don't know what they are doing...


    <FlameWar>
    Well if they knew, they wouldn't be writing in PHP!!! :)
    </FlameWar>
  • Schmalls 2009-10-26 10:43
    mbvlist:

    It doesn't work like that when in a string AFAIK. You can test it using this code:
    $array['true'] = 'The Real WTF is PHP syntax.';
    $var1 = "$array[true]";
    $var2 = $array['true'];

    I think $var1 and $var2 have the same value. Don't ask me why, it is pretty much crap anyway.

    You are correct. It doesn't matter since the argument does hold for Jim's code:
    $hostid = $aservers[$i][hostid];
    
    $hostname = $aservers[$i][hostname];
  • Airhead 2009-10-26 10:53
    Myname!:
    The suggested code is a WTF in itself. If the value doesn't exist, then there's no need to set the result to "null" because it's already the type NULL which would turn into "null" at any string conversion. If the value was an empty string as the bad code suggested then isset() would return true and it'll stay as "".


    Setting variables is A Good Thing. If you need to check for that variable later, you don't allways have to check it with

    <?php
    if (isset($variable) && $variable != null)
    ....
    ?>

    Some of us use debugging with php.
  • Airhead 2009-10-26 10:58
    Severity One:
    FragFrog:
    ...but to write truely good PHP code is both possible as well as just as hard as writing good code in any other language.

    I would say it's a lot harder. :)

    So, you don't know PHP? ;)
  • Martin 2009-10-26 11:07
    EatenByAGrue:
    The real question is whether Jim's reporting application generated paper reports that could be faxed to the head office, placed on a wooden table, photographed, and the photograph emailed out.


    How can you please email a photograph? The photograph needs to be developed and scanned before emailing.

    Stick to the process in future!
  • Beaker 2009-10-26 11:10
    EatenByAGrue:
    The real question is whether Jim's reporting application generated paper reports that could be faxed to the head office, placed on a wooden table, photographed, and the photograph emailed out.


    Sadly, that feature is not implemented yet. There are links on the page, and the managers are afraid that they might accidentally click on them. That would be very confusing for the user, so they need to find a way to disable any links before they can fax reports.

  • justsomedude 2009-10-26 11:23
    Anonymous:
    MyKey_:
    [UPDATE: Sorry, I forgot the mandatory http://xkcd.com/138/.]

    XKCD currently has the best Geocities commemoration I've ever seen - complete with blink tags, broken images and malformed HTML aplenty. It looks exactly like any Geocities page of the nineties. Good times.



    94 Errors, 22 warning(s)
    Oh Baby! LOL @ <HTML WEB="2.0"> and the GOTO 10 tag.


  • Anthony 2009-10-26 11:51
    mbvlist:
    Schmalls:


    No the quotes aren't redundant. It is doing the same thing as:
    $x[hostid] . '.' . $x[hostname]
    However, a big WTF is that the array key isn't quoted like so:
    $x['hostid'] . '.' . $x['hostname']
    When left unquoted, PHP first checks to see if there are constants named hostid and hostname and if there are none it emits a notice and uses the string instead.

    It doesn't work like that when in a string AFAIK. You can test it using this code:
    $array['true'] = 'The Real WTF is PHP syntax.';
    $var1 = "$array[true]";
    $var2 = $array['true'];

    I think $var1 and $var2 have the same value. Don't ask me why, it is pretty much crap anyway.


    Correct, because within quotes it will never evaluate it to a constant (unless using the constant() function).

    What Schmalls was getting at is this

    $array['true'] = 'The Real WTF is PHP syntax.';
    $var1 = "$array[true]";
    $var2 = $array['true'];
    $var3 = $array[true];

    $var1 === $var2 != $var3

    Now, there is ambiguity in the quoted variable syntax. That's why I try to avoid it completely. But if I do it, I'll use the curly brace syntax to force the variable. So instead of "$array[true]", it would be "{$array['true']}".. That allows you to also do things like "{$word}[something]" without it trying to parse it as an array...
  • Jay 2009-10-26 12:16
    Kermos:
    Dunno if I can really say WTF here. The story itself clearly states this guy had absolutely no programming background and apparently, when he first wrote this application, I it doesn't appear there were any developers available to hand the task off to.

    Given that the developer team later on didn't completely scrap the entire code base and was able to refactor it to me indicates that overall, it couldn't have been *that* bad. I think primarily the project just grew to a size where this guy could no longer handle it with his limited experience.

    I think we all can agree that every one of us has produced WTF Worthy code when we first started writing software.

    Had this guy been someone claiming to be the greatest programmer of all time with a 6 digit salary, then yes, I'd definitely say WTF. But seeing how the story clearly states he was a beginner, I'd say rather than pointing at him and screaming WTF, someone should maybe consider giving a person like that some pointers in how to do things better. Never know, might actually get a great developer out of it eventually...



    If an self-trained person on his first attempt at programming writes code that is so bad that it's funny, it is unfair to ridicule him. How do you expect him to learn until he gains some experience?

    But the code is still funny.

    And just because it's unfair to ridicule someone doesn't mean that we don't enjoy doing it.
  • Jay 2009-10-26 12:23
    Beaker:
    EatenByAGrue:
    The real question is whether Jim's reporting application generated paper reports that could be faxed to the head office, placed on a wooden table, photographed, and the photograph emailed out.


    Sadly, that feature is not implemented yet. There are links on the page, and the managers are afraid that they might accidentally click on them. That would be very confusing for the user, so they need to find a way to disable any links before they can fax reports.



    I wouldn't be surprised if in a couple of decades we don't have paper thin computers that you CAN handle like a sheet of paper and poke your finger on a link to bring up the referenced page. And then people will read old jokes about links on print-outs and scratch their heads saying, "I don't get it. So the print-out had links in the text. What's the joke?"

    I saw a comedy that was made in the 60s where a guy is trying to bluff his way through a job interview. He's asked if he has any experience working with computers, and he says yes. Then he's asked where he gained this experience, and he says "My aunt had a computer." In the 60s this must have seemed absurd, like claiming that your aunt had a nuclear reactor in her tea room. But of course today, I'm sure many people have aunts who have computers at home.

  • Anonymous 2009-10-26 12:27
    justsomedude:
    Anonymous:
    MyKey_:
    [UPDATE: Sorry, I forgot the mandatory http://xkcd.com/138/.]

    XKCD currently has the best Geocities commemoration I've ever seen - complete with blink tags, broken images and malformed HTML aplenty. It looks exactly like any Geocities page of the nineties. Good times.

    94 Errors, 22 warning(s)
    Oh Baby! LOL @ <HTML WEB="2.0"> and the GOTO 10 tag.

    My favourite:

    <SCRIPT LANGUAGE="QBASIC">IF $BROWSER = "IE" THEN GOTO 50</SCRIPT>

    ...also the single <JAVA> tag that appears for absolutely no reason.
  • BentFranklin 2009-10-26 12:50
    Jay:
    I saw a comedy that was made in the 60s where a guy is trying to bluff his way through a job interview. He's asked if he has any experience working with computers, and he says yes. Then he's asked where he gained this experience, and he says "My aunt had a computer." In the 60s this must have seemed absurd, like claiming that your aunt had a nuclear reactor in her tea room. But of course today, I'm sure many people have aunts who have computers at home.


    Unless your aunt was Grace Hopper.
  • Procedural 2009-10-26 12:53
    Jim:
    Now that I am redundant, I would just like to say that it's no fun being redundant.


    That's completely true.
  • evilspoons 2009-10-26 12:54
    I'm surprised no one's mentioned the irony of Jim writing the system that was used to replace Jim.
  • Rocketeer 2009-10-26 12:56
    I enjoyed reading that code - it was like a horror story for programmers :-)


    $hostid = $aservers[$i][hostid];
    $hostname = $aservers[$i][hostname];
    $systemkey = $hostid . "." . $hostname;

    It started off with a little light foreboding - just as we all know "It was a dark and stormy night..." is going to lead to trouble, so does gratuitous variable creation.


    for ($j=0; $j < count($akeys); $j++) {
    if ($systemkey == $akeys[$j]) {
    $ainstall_values[$i] = $ainstall[$systemkey];
    }
    }

    Then, as the story progresses, we start to feel fear at the unnecessary inner loop... okay, so far, it's a touch amateurish, but that's to be expected - yes, there's an easier way to do all this, but it's not actually bad per-se...


    // PHP has an eval function like perl.
    // Building up a switch statement to run later.
    $switch = "switch (\$ainstall[\$systemkey]) {";
    $avalues[count($aunique)];

    Then, like a scream cutting through the night... Eval? Nominative determinism raises it's head - just as Jack the Ripper is unlikely to be planning to convert your CDs to MP3s, a function named Eval is unlikely to be planning on anything good...

    To be honest, at this point I went and hid behind the sofa... I heard some more screaming, and a mechanical voice declaiming "E-val-u-ate... E-val-u-ate..." but I didn't dare look at the screen again until the end credits started rolling!
  • nube 2009-10-26 13:12
    Why is this sort of thing a web application ? A system type person should know better.
  • EngleBart 2009-10-26 13:33
    highphilosopher:
    Unfortunately it's people like this that give PHP a bad name. There's nothing wrong with PHP, just something wrong with learning any language in 21 days.
    I think the problem is that he learned PHP and how to program in 21 days!

    A programmer with a solid foundation in a single language should be able to produce workable code (not necessarily pretty) in a new language. (If there is a major paradigm shift, e.g. procedural to functional or procedural to tree(XSLT), add a few months for the brain to re-plasticize)
  • ZP 2009-10-26 13:35
    Anon Ymous:
    The_Assimilator:
    Jim aggressively fought off all attempts at transitioning the application the development team so, during a round of cost cutting, Jim was made redundant.


    PHP Parse error: parse error: supplied sentence does not contain valid grammar in C:\Inetpub\wwwroot\tdwtf\Articles\PHP-has-an-eval-function-like-perl.aspx on line 5


    There's nothing wrong with the grammar of that sentence. "Fight off" is a phrasal verb -- it has a different meaning than "fight". (Or are you whining about the use of the passive voice?)


    You completely missed the whole.
  • Dan 2009-10-26 13:47
    Since it would have been wasteful to rewrite it from scratch, there are still vestiges of Jim in there


    In my experience, it's sometimes better to learn from the first attempt, then scrap it entirely and rewrite it. You often come up with better organization and improve maintainability to the nth degree that way. I've been involved in too many projects where "we don't have time to really fix it, so just fix the problem" and the "just fix it" only made the code harder to work with and often introduced even more problems.
  • dtaylor84 2009-10-26 13:56
    Actually, no. In that example PHP is interpolating the string, not evaluating the string. Both can be problematic, at times, but interpolating input is a whole lot less likely to get you in trouble than evaluating input.
  • Procedural 2009-10-26 14:08
    EngleBart:
    highphilosopher:
    Unfortunately it's people like this that give PHP a bad name. There's nothing wrong with PHP, just something wrong with learning any language in 21 days.
    I think the problem is that he learned PHP and how to program in 21 days!

    A programmer with a solid foundation in a single language should be able to produce workable code (not necessarily pretty) in a new language. (If there is a major paradigm shift, e.g. procedural to functional or procedural to tree(XSLT), add a few months for the brain to re-plasticize)


    I hear they may possibly hypothetically be writing a follow-up to "Learn PHP in 21 Days". It's be called "Unlearn Your Hack Habits in 2.5 Years".

    It may not sell as much, but the market is huge.
  • Ralph 2009-10-26 14:19
    Anthony:


    Correct, because within quotes it will never evaluate it to a constant (unless using the constant() function).

    What Schmalls was getting at is this

    $array['true'] = 'The Real WTF is PHP syntax.';
    $var1 = "$array[true]";
    $var2 = $array['true'];
    $var3 = $array[true];

    $var1 === $var2 != $var3

    Now, there is ambiguity in the quoted variable syntax. That's why I try to avoid it completely. But if I do it, I'll use the curly brace syntax to force the variable. So instead of "$array[true]", it would be "{$array['true']}".. That allows you to also do things like "{$word}[something]" without it trying to parse it as an array...


    Using true here is an array key is a bad example, because its also reserved for boolean truth, but the PHP wtf is that:

    $array['key'] = 'value';

    $var1 = $array['key'];
    $var2 = $array[key]

    Now $var1 === $var2, but you will get a warning on the line assigning $var2 about using constants as an array key, but the interpreter will guess your intention and use the string if it finds it. === is an operator that checks both type and value, so:

    1 == "1" //true
    1 === "1" //false

    More WTF,

    $int = 1;
    $string1 = "the value of int is $int";
    $string2 = 'the value of int is $int';

    $string1 will contain "the value of int is 1", while $string2 is "the value of int is $int" , single quotes are dumb strings, but when double quotes are used the interpreter will look at your string and insert any variables it finds.
  • JRiddy 2009-10-26 14:42
    BentFranklin:

    Unless your aunt was Grace Hopper.


    Nice reference.
  • Shishire 2009-10-26 15:04

    <?php
    define('foo', 'bar');

    $var[foo] = 'baz';
    $var['foo'] = 'random';

    echo "\$var[foo] = $var[foo]\n";
    echo "\$var[bar] = $var[bar]\n";
    echo '$var[\'foo\'] = '.$var['foo']."\n";
    echo '$var[foo] = '.$var[foo]."\n";
    echo '$var[\'bar\'] = '.$var['bar']."\n";

    ?>

    Output:

    $var[foo] = random
    $var[bar] = baz
    $var['foo'] = random
    $var[foo] = baz
    $var['bar'] = baz


    The point here being that single and double quotes do different things, constants are resolved first, and that array keys inside of single quotes don't need to be re-quoted.

    That being said, imho, it's never a good idea to mix variables into static strings, which is why I always use single quotes, and break out whenever I need to insert a variable. Much safer, and no messy escape syntax to deal with (with the exception of ' and \ ).

    Captcha: odio
    Odious much?
  • cfreak 2009-10-26 15:19
    mbvlist:
    Schmalls:


    No the quotes aren't redundant. It is doing the same thing as:
    $x[hostid] . '.' . $x[hostname]
    However, a big WTF is that the array key isn't quoted like so:
    $x['hostid'] . '.' . $x['hostname']
    When left unquoted, PHP first checks to see if there are constants named hostid and hostname and if there are none it emits a notice and uses the string instead.

    It doesn't work like that when in a string AFAIK. You can test it using this code:
    $array['true'] = 'The Real WTF is PHP syntax.';
    $var1 = "$array[true]";
    $var2 = $array['true'];

    I think $var1 and $var2 have the same value. Don't ask me why, it is pretty much crap anyway.


    So true. PHP took all the worst parts of Perl, C and more recently Java, blended them together and called it a "language"

    (I'm allowed to say that because I write PHP for a living)
  • cfreak 2009-10-26 15:29
    Ralph:

    More WTF,

    $int = 1;
    $string1 = "the value of int is $int";
    $string2 = 'the value of int is $int';

    $string1 will contain "the value of int is 1", while $string2 is "the value of int is $int" , single quotes are dumb strings, but when double quotes are used the interpreter will look at your string and insert any variables it finds.


    That's a Perlism and it really does make sense: interpolating can be slower, if you know you aren't going to be interpolating a variable it gives you a bit of a performance boost and the added security to know someone can't externally muck with your string. It's also convenient if you need literal $ signs in your string (and in perl more so since it uses other symbols like @ and % for arrays and hashes)
  • Medezark 2009-10-26 15:53
    I would hate for anyone to have too look at my current code, much less the code I wrote in the period during or immediately after learning a new language.
  • pitchingchris 2009-10-26 16:53
    Medezark:
    I would hate for anyone to have too look at my current code, much less the code I wrote in the period during or immediately after learning a new language.


    So how are you at working in a team? In order to work effectively, you have to be able to let your peers review your current code.
  • Medezark 2009-10-26 17:08
    pitchingchris:
    Medezark:
    I would hate for anyone to have too look at my current code, much less the code I wrote in the period during or immediately after learning a new language.


    So how are you at working in a team? In order to work effectively, you have to be able to let your peers review your current code.


    Teams are so gay. Peer reviews even gayer.
  • Malenfant 2009-10-26 17:20
    Medezark:
    pitchingchris:
    Medezark:
    I would hate for anyone to have too look at my current code, much less the code I wrote in the period during or immediately after learning a new language.


    So how are you at working in a team? In order to work effectively, you have to be able to let your peers review your current code.


    Teams are so gay. Peer reviews even gayer.


    With an attitude like that, I really wish you would put some of your code up on here. I'm sure we'd all enjoy it
  • Medezark 2009-10-26 17:22
    Malenfant:
    Medezark:
    pitchingchris:
    Medezark:
    I would hate for anyone to have too look at my current code, much less the code I wrote in the period during or immediately after learning a new language.


    So how are you at working in a team? In order to work effectively, you have to be able to let your peers review your current code.


    Teams are so gay. Peer reviews even gayer.


    With an attitude like that, I really wish you would put some of your code up on here. I'm sure we'd all enjoy it.


    You are so gay.
  • dunawayc 2009-10-26 17:49
    FragFrog:
    A LOT of crap gets written in PHP because people don't know what they are doing, ... It's just that PHP makes writing bad code so much easier


    PHP == VB ??

  • iusto 2009-10-26 18:12
    JRiddy:
    BentFranklin:

    Unless your aunt was Grace Hopper.


    Nice reference.

    Wikipedia:
    "In 1985, the rank of Commodore was renamed Rear Admiral, Lower Half."

    WTF?!?!?

    I suppose we should be grateful it's not "Rear Admirer, Left Half"...
  • dkf 2009-10-26 19:08
    Anonymous:
    My favourite:
    <SCRIPT LANGUAGE="QBASIC">IF $BROWSER = "IE" THEN GOTO 50</SCRIPT>
    ...also the single <JAVA> tag that appears for absolutely no reason.
    Well, there's also the random piece of almost-C++, the <FONT STYLE="FORTHRIGHT"> (ok, I shortened it), the <TABLE CONS=()>, and the chunk of Scheme that's sitting in its own <SCRIPT> tag. Did anyone ever implement a browser which could handle that? (Also, is
    <LANG="AMERICAN/ESPA☃ISH">
    misencoded, or is it a feature of my browser? Right now, I could believe either.)

    Overall, it brings back so many memories of When the Web Web was Young. Mostly bad ones. My eyes hurt whether I look at the source or the rendered page. (Animated backgrounds? That are mostly the same color as the text? Webrings? A "best viewed in" blurb? Oh my!) If it hadn't been deliberate, it would have been perfect. As it is, it's slightly too clever. Scary too. It really was that bad. Still is in some parts of the 'net.

    (Randall, if you're reading this... the blink tricks didn't work on Safari. More javascript was needed. I suppose that would have fitted in just perfectly with the rest of that monstrous masterpiece...)
  • captain obvious 2009-10-26 19:28
    Former statement's correct, latter is not. The dot in the middle is part of the string.

    Nevertheless, this is bad coding practice, as a) it is unreadable, and b) the array key is parsed as a constant. If someone created a constant named "hostname", the code would most likely fail.

    Finally, who the fuck names a variable $ainstall and all in lowercase?
  • 50% Opacity 2009-10-26 19:49

    foreach ($aservers as $x) {
    $type = $ainstall["$x[hostid].$x[hostname]"];
    if (! isset($type)) $type = 'null';
    $avalues[$type]++;
    }


    Shouldn't that be:


    foreach ($aservers as $x) {
    $type = 'null';
    if (isset($ainstall["$x[hostid].$x[hostname]"])) {
    $type = $ainstall["$x[hostid].$x[hostname]"];
    }
    $avalues[$type]++;
    }


    In the proposed code, $type is clearly being set, but it may or may not be empty().
  • Gaylord 2009-10-26 20:01
    Medezark:
    Malenfant:
    Medezark:

    Teams are so gay. Peer reviews even gayer.

    With an attitude like that, I really wish you would put some of your code up on here. I'm sure we'd all enjoy it.

    You are so gay.

    Why honey, you looking for some?
  • 50% Opacity 2009-10-26 20:06
    And to everybody who still didn't get the "$var[name]" problem:

    It's a special case for the parser. PHP does NOT see a constant called "name" here.


    $var['name'] == "$var[name]" == "{$var['name']}";
    $var['name']['name2'] != "$var[name][name2]";


    PHP interprets one dimension of array keys in strings with no quotes. Two or more need to be put in curlies {} and quoted as usual.

    I'd post a link to the manual, but apparently that makes me a spammer. Look for "string parsing" on php.net yourself.
  • Mones Adwan 2009-10-26 20:49
    I spent more than five years in teaching and developing using PHP and MYSQL. And I feel that I have a right to say that the most thing I hate in that domain is spending most of the time in discussing the code it self rather than what the code could do.
  • chunder thunder 2009-10-26 20:53
    Rocketeer:
    I enjoyed reading that code - it was like a horror story for programmers :-)


    $hostid = $aservers[$i][hostid];
    $hostname = $aservers[$i][hostname];
    $systemkey = $hostid . "." . $hostname;

    It started off with a little light foreboding - just as we all know "It was a dark and stormy night..." is going to lead to trouble, so does gratuitous variable creation.


    If you're only going to use the variables once, I agree... though I think in some cases it can improve code readability. This is especially true when either you use the same datum more than once or the array lookup is deep. In the former case, it saves you trying to figure out if two long array dereference sequences are actually identical or just similar.

    Of course, since it's essentially a form of code self-documentation, it's subject to the usual worries about keeping documentation in sync with the actual code...
  • AndyCanfield 2009-10-26 21:56

    $type = 'null';
    if (isset($ainstall["$x[hostid].$x[hostname]"])) {
    $type = $ainstall["$x[hostid].$x[hostname]"];

    The drawback here is that you have to hope and pray that the second $ainstall line matches the first $ainstall line exactly. For short lines that can be confirmed visually; for lines as long as this I'd rather do it once and cope with the results. Even if they match today, they may not match after somebody takes a text editor to your source file.
  • 50% Opacity 2009-10-26 22:48
    AndyCanfield:

    $type = 'null';
    if (isset($ainstall["$x[hostid].$x[hostname]"])) {
    $type = $ainstall["$x[hostid].$x[hostname]"];

    The drawback here is that you have to hope and pray that the second $ainstall line matches the first $ainstall line exactly. For short lines that can be confirmed visually; for lines as long as this I'd rather do it once and cope with the results. Even if they match today, they may not match after somebody takes a text editor to your source file.


    You could, you know, check. The point is though, that the original version does this:

    1. Create variable $type and assign it a value which may or may not exist, which may throw a warning.
    2. Check if variable $type isset, which it definitely always is, because it was declared on the line before.
    3. If $type is not set (never the case), assign it the default value 'null'.

    What I'm proposing is:

    1. Initialize variable $type to default value 'null'.
    2. Check if the value I actually want is available.
    3. If it is, assign value I actually want to $type.

    No chances of throwing an error and no unused code branches. The original is simply nonsense. If you're paranoid about mistyping the $ainstall variable, do this:


    $type = 'null';
    $key = "$x[hostid].$x[hostname]";
    if (isset($ainstall[$key])) {
    $type = $ainstall[$key];
    }
  • 50% Opacity 2009-10-26 22:58
    50% Opacity:

    2. Check if variable $type isset, which it definitely always is, because it was declared on the line before.


    Okay, sorry, scratch that part. !isset($type) is true if $type === null. What still holds true is that you'll get a warning for a missing array key in step one. So instead of getting a warning and dealing with it later I'm proposing a warning-less way, which should always be preferred.
  • nwbrown 2009-10-27 00:21
    So the WTF is what, that instead of hiring a trained programmer to develop the tool, they had some untrained guy who had simply read a "Learn ${Some_Language} in 21 Days" book do it? I'm curious what these managers think we are doing in the 4 years we spend getting a degree in college if they think programming can be learned in 21 days...

    I wonder if I bought a "Learn People Management in 21 Days" book, would upper management would let me become a vice president of something?
  • burpy 2009-10-27 02:45
    dunawayc:
    FragFrog:
    A LOT of crap gets written in PHP because people don't know what they are doing, ... It's just that PHP makes writing bad code so much easier


    PHP == VB ??



    Funny that you mention it. How come we never see WTFs written in real programming languages??? Always in Personal Home Page or visual "look look, I made a window with a textbox" basic!
  • Jan 2009-10-27 03:13
    > Or maybe he was a dumbass.

    He was not a dumbass. This was a clever solution from someone who has obviously no programming experience whatsoever.

    The real WTF is not the programmer fucking up, but management allowing such a system to grow over the years without ANY feedback from real developers.

    Programming is hard; allowing someone who is not a programmer to build a large and obviously important application is asking for trouble. Nobody does these things right the first time without some guidance.
  • roger 2009-10-27 03:48
    Jan:
    > Or maybe he was a dumbass.

    He was not a dumbass. This was a clever solution from someone who has obviously no programming experience whatsoever.

    The real WTF is not the programmer fucking up, but management allowing such a system to grow over the years without ANY feedback from real developers.

    Programming is hard; allowing someone who is not a programmer to build a large and obviously important application is asking for trouble. Nobody does these things right the first time without some guidance.


    Come one, we all know a computer guy is a computer guy. There's no real difference between a programmer, a dba and the guy who changes your keyboard when it's broken...
  • Kiss me I'm Polish 2009-10-27 04:27
    So the guy had an idea about automating the most dumbass tasks and have them online.
    He hacks a website that does exactly that.
    Then mister smartass shows up, takes a look at the code and sends it to thedailywtf. "OMG! Look, he stupid! He shouldn't be doing php!"
    But that's not all. Mr smartass shows how it should be done! Only he doesn't realize his code sucks too.

    Now that's a wtf.
  • The Troll 2009-10-27 04:42
    On some whim, I've always avoided PHP. Looking at all the code on this issue, I can see why. TRWTF really is the language, this time. The code from the "experienced" guy look almost as bad as the code from the newbie. Laughing at code from a newbie is really not cool.

    CONSEQUAT: There will be
  • winstein 2009-10-27 06:38
    I see these kinds of examples posted a lot in discussions regarding php, and Ive never really understood why.

    who cares? perfect logical inconsistency is a ridiculous goal in any language, and the advantages of php hugely outweigh the occasional linguistic oddity that no decent programmer ever has a problem with *anyway* because they just dont write code that looks like:

    if($var['name']['name2'] != "$var[name][name2]")


    its is inane to pretend that the existence of such linguistic oddities are sufficient in themselves to render a language good or bad.




  • Anonymous 2009-10-27 06:41
    Mones Adwan:
    I spent more than five years in teaching and developing using PHP and MYSQL. And I feel that I have a right to say that the most thing I hate in that domain is spending most of the time in discussing the code it self rather than what the code could do.
    Then why are you here? Quit discussing and get coding if that's how you feel.
  • Stuart 2009-10-27 09:10
    Hello, I'm Stuart. I'd like to clarify some things:

    Jim had a great idea, and his website is still in use today - now that it's cleaned up, we can trust the data in it, the pages load within a minute, and it's available for more than a couple of hours a day. It saves all the sysadmins huge amounts of time.

    We have other websites developed by sysadmins who still have their jobs. The difference is they knew when to let go - they handed over their babies to the development team for ongoing maintenance and they got back to being good sysadmins rather than poor programmers.

    Jim had several years to learn proper development practices, but he believed his tinkering was good enough programming. Nobody cared to look under the hook and challenge him about it, so he didn't bother learning any more. Nobody worried about this until things started coming unstuck. The code you see here is not a beginner's first attempts, it's from someone "with several years development experience".

    Much of Jim's code is what you'd expect from a non-programmer, which is not a WTF in itself, but this snippet is such a complicated and convoluted way of doing a task that I couldn't work out why he'd ever choose to do it that way.

    The example code is just there to show what Jim's code is trying to do, but in a concise fashion, so you can see what $aservers, $ainstall and $avalues mean. The code in production does a COUNT at the database instead. I apologise for the isset() rather than array_key_exists(), it's a Perlism taken over to PHP.
  • TiS 2009-10-27 09:13
    AndyCanfield:

    $type = 'null';
    if (isset($ainstall["$x[hostid].$x[hostname]"])) {
    $type = $ainstall["$x[hostid].$x[hostname]"];

    The drawback here is that you have to hope and pray that the second $ainstall line matches the first $ainstall line exactly. For short lines that can be confirmed visually; for lines as long as this I'd rather do it once and cope with the results. Even if they match today, they may not match after somebody takes a text editor to your source file.


    Well, most modern editors have functions like copy-paste.

    It clearly could be better to do it once, but as Andy said, this code throws a warning. To be exact:
    Notice: Undefined index: t.t in wtf.php on line 9

    if the index does not exists. Ofc, maybe it always exists, and this discussion is pointless. But in most cases like this one, it MAY not exist.

    Then, you can say that the notice error is not an error as-is and we can deal with it. In many cases you're right, but in a case of debugging and looking through logs the avalanche of notices can be overwhelming. And sometimes there's no good way of debug. I'm currently working with heavily AJAXed and framed spaghetti code, the only place I can use to debug are sometimes logs. Two pages of notices for one request can be a little bit disappointing, not to say it's hard to find something useful in there.
  • Ozz 2009-10-27 11:57
    ZP:
    You completely missed the whole.
    That's what she said...
  • Zach 2009-10-27 13:48
    LOL @ xkcd!
  • Fedaykin 2009-10-27 13:48
    Anon Ymous:
    The_Assimilator:
    Jim aggressively fought off all attempts at transitioning the application the development team so, during a round of cost cutting, Jim was made redundant.


    PHP Parse error: parse error: supplied sentence does not contain valid grammar in C:\Inetpub\wwwroot\tdwtf\Articles\PHP-has-an-eval-function-like-perl.aspx on line 5


    There's nothing wrong with the grammar of that sentence. "Fight off" is a phrasal verb -- it has a different meaning than "fight". (Or are you whining about the use of the passive voice?)


    That sentence is gibberish. Luckily, you are familiar with the context of the sentence so you are able to understand it and your brain doesn't see the error. The part your brain is unjumbling is easier to see as broken when it's outside the context of the sentence:

    "transitioning the application the development team so"

    Also, it has a nasty comma splice.

    What the author meant to write:

    Jim aggressively fought off all attempts at transitioning the application to the development team. So, during a round of cost cutting, Jim was made redundant.

  • Jay 2009-10-27 14:45
    nwbrown:
    So the WTF is what, that instead of hiring a trained programmer to develop the tool, they had some untrained guy who had simply read a "Learn ${Some_Language} in 21 Days" book do it? I'm curious what these managers think we are doing in the 4 years we spend getting a degree in college if they think programming can be learned in 21 days...

    I wonder if I bought a "Learn People Management in 21 Days" book, would upper management would let me become a vice president of something?


    I just read "Learn Open Heart Surgery in 21 Days". (I skipped a couple of chapters because all that stuff about blood was too gross.) Now I'm going to apply for a job as a surgeon.
  • Fedaykin 2009-10-27 14:48
    In my current job I work in a development group for a large organization with many offices that often have amateur applications crop up in that we take over and fix when it becomes apparent they are useful on a larger scale.

    If you were able to refactor this application and make it work, then it was a damn fine amateur effort and certainly not a WTF.

    If I could share some of the code from the applications I've taken over (and had to rewrite from the step of requirements gathering), THEN you would know the true meaning of WTF.
  • Jay 2009-10-27 15:20
    Or better yet ... I think I'm going to call the publisher of these "Learn ... in 21 Days" books and tell them that I just read "Learn How to Write 'Learn in 21 Days' Books in 21 Days" and ask them if they'll give me a book contract with a big advance.
  • rfsmit 2009-10-27 16:10
    EmperorOfCanada:
    Maybe he had tonnes of Lisp/AI experience and was planning on building a self coding dynamic intelligent system?
    Or maybe he was a dumbass.
    Or maybe he was a sysadmin with no programming experience who fulfilled his original aim in a short amount of time?
  • rfsmit 2009-10-27 16:13
    TiS:
    AndyCanfield:
    Even if they match today, they may not match after somebody takes a text editor to your source file.


    Well, most modern editors have functions like copy-paste.

    I'll let that stand as a testament to ignorance.
  • Peter 2009-10-27 20:24
    http://www.ietf.org/rfc/rfc1760.txt

    The S/KEY system is designed to facilitate this manual entry without impeding automatic methods. The one-time password is therefore converted to, and accepted as, a sequence of six short (1 to 4 letter) English words. Each word is chosen from a dictionary of 2048 words;

    Dictionary for Converting Between S/KEY 6-Word and Binary Formats

    { "A", "ABE", "ACE", ....."YELL", "YOGA", "YOKE" };
  • Peter 2009-10-27 20:28
    Ooops - I put my comment in the wrong thread.
  • besthdsoft2 2009-10-27 22:53
    Blu-ray Ripper is Blu-ray converter, Blu-ray ripper, Blu-ray rip software to convert Blu-ray, rip blu ray to avi, DivX, MPEG, WMV, MP4, WMA, MP3 easily and quickly.
  • TiS 2009-10-28 04:39
    rfsmit:
    TiS:
    AndyCanfield:
    Even if they match today, they may not match after somebody takes a text editor to your source file.


    Well, most modern editors have functions like copy-paste.

    I'll let that stand as a testament to ignorance.


    That's why you have tests on application (like, unit tests and so). You have them, right?
    Ok, jokes over. You have in perfect world, but...
    If you want 'editor-safer' approach you can do it like that

    Ah, 50% Opacity already wrote this
    $key = "$x[hostid].$x[hostname]";
    
    if (isset($ainstall[$key]))
    $type = $ainstall[$key];
    (in fact I write like that in more complex keys I have to use more than once)

    or, if you preffer dirty approach
    $key = "$x[hostid].$x[hostname]";
    
    $type = isset($ainstall[$key])?$ainstall[$key]:'null';

    But the overall approach should always be - FIRST test if something exists, THEN use it. It's better practice, other languages aren't as permissive as PHP.
  • Psyckers 2009-10-28 16:26
    My word, the parallels of "PHP has an eval function like perl" here is unprecidented since we are needing to recode a number of 'systems' that had evolved just like this example. The fact that the guy who did it to us is also called Jim is spooky at best.
    Is it possible to discriminate against network admins that are named Jim?
  • FoolishOwl 2009-10-28 17:21
    I keep reading posts about sysadmins who don't know how to program. This puzzles me, given all the programming courses I'm taking in order to qualify as a sysadmin.
  • Ouch! 2009-10-28 20:15
    FoolishOwl:
    I keep reading posts about sysadmins who don't know how to program. This puzzles me, given all the programming courses I'm taking in order to qualify as a sysadmin.

    Maybe it used to be different and they included programming courses in the curriculum as a reaction to all those WTFs?
  • Optimus Dime 2009-10-30 10:24
    Schmalls:
    noway!:
    FragFrog:
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.

    That's variable expansion, not code evaluation. Although, i think the quotes are redundant... right?


    No the quotes aren't redundant. It is doing the same thing as:
    $x[hostid] . '.' . $x[hostname]
    However, a big WTF is that the array key isn't quoted like so:
    $x['hostid'] . '.' . $x['hostname']
    When left unquoted, PHP first checks to see if there are constants named hostid and hostname and if there are none it emits a notice and uses the string instead.

    And this is why PHP is retarded.

    Arcane parsing rules are TRWFT.
  • savar 2009-10-30 14:35
    FragFrog:
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.



    Are you being serious? It gets interpolated, not eval'ed. Big difference.
  • anonymous 2009-11-01 17:26
    There is a massive difference between copying the syntax from a book and learning a language.

    But yeah, you can write bad code in any language if you try hard enough, try this beauty from the our application that I found just now in our mature, widely used java app (This is not a unique example).

    StringBuffer sqlStmtStr = new StringBuffer();
    ....
    sqlStmtStr .append("AND f.name = " + nameStr + " " );
    ....


    ahhh, what a day I have infront of me.

  • Jeh-fuh-fuh 2009-11-02 18:39
    FragFrog:
    And it keeps saddening me to see things like this:

    $type = $ainstall["$x[hostid].$x[hostname]"];

    Guess what you're doing? That's quite right: in your bright, shiny example you are letting PHP eval that string, the very same principle you're bashing the original writer for.

    Erm, no you're not - while it's not how I would have done it, is essentially doing: 1) resolve var values 2) concatenate 3) do a hashmap lookup. There's no eval involved.


    A LOT of crap gets written in PHP because people don't know what they are doing, but to write truely good PHP code is both possible as well as just as hard as writing good code in any other language. It's just that PHP makes writing bad code so much easier :]


    Actually no, you're wrong. It's not possible to write truly good PHP code.
  • Jeh-fuh-fuh 2009-11-02 18:45
    Airhead:
    Severity One:
    FragFrog:
    ...but to write truely good PHP code is both possible as well as just as hard as writing good code in any other language.

    I would say it's a lot harder. :)

    So, you don't know PHP? ;)

    I daresay the problem is that he does know it.
  • Jeh-fuh-fuh 2009-11-02 18:48
    Dan:
    Since it would have been wasteful to rewrite it from scratch, there are still vestiges of Jim in there


    In my experience, it's sometimes better to learn from the first attempt, then scrap it entirely and rewrite it. You often come up with better organization and improve maintainability to the nth degree that way. I've been involved in too many projects where "we don't have time to really fix it, so just fix the problem" and the "just fix it" only made the code harder to work with and often introduced even more problems.

    But scrapping the code and rewriting it /never/ has problems, right? I mean - it's always flawless out the gate... ;)