Jeremy Smith's blog

Entry Is Labelled

OddPHP

In Greg's comment on the post Advice for Hiring Perl Programmers:

Where's the PHP quiz? Oh, wait, PHP is easily readable. Sorry for asking. ;)

<flamewar start="now">

Without executing it (because that would be cheating, tell me what the following prints out):

$a = 13;

print("$a<br />");

foo(&$a);

print("$a<br />");

bar($a);

print("$a<br />");

baz($a);

print("$a<br />");

function foo($a)
{
  $GLOBALS['a']++;
  print("$a<br />");
}

function bar(&$a)
{
  $GLOBALS['a']++;
  print("$a<br />");
}

function baz($a)
{
  $GLOBALS['a']++;
  print("$a<br />");
}

?>

Comments

  1. gravatar

    print("$a
    "); will send the output "13
    "

    the foo(&$a) syntax is deprecated in PHP 5 and should issue a PHP warning to that effect. The correct way to do pass-by-reference is:
    function foo (&$a) { blah; }

    As written, the foo function will take $a (by reference). The access to the GLOBALAL array of a will increment the global a by one. Since this variable is passed by reference, the locally scoped variable $a also gets incremented by one. The first foo call should thus output "14
    ". Also worth noting that global variable usage is semi-bad programming practice and variables should be passed into function calls instead of brought in globally.

    the bar function is the correct way of passing variables by reference. foo(&$a) and function foo(&$a) are functionally identical.

    Print after foo(&$a) will be the same output is the call to foo(&$a) "14
    "

    bar call does same as foo. Outputs "15
    ";
    print call after it outputs "15
    ";

    baz is pass by value, to the global variable is updated, but local isn't so output is still "15
    ";

    Finally, you get output of "16
    "

    So, final output is 13 14 14 15 15 15 16

    A worthy test, but only on the PHP's variable references, which I admin can be confusing to new-comers, but it easy to master. The only real issue I have with PHP is remembering parameter order, especially for some of the string and array functions. Consulting php.net solves the problem rather quickly. The only other thing I see really tricking people up is variable comparison. 0 !== false !== null !== '0'.

    What is legal syntax:

    if ($a && $b) {
    echo "foo";
    }

    OR

    if ($a and $b) {
    echo "foo";
    }