Desugaring PHP syntax

1.9k views Asked by At

As part of learning PHP, I'm trying to formalize its semantics. A great way to simplify this task is to understand as much of its syntax as possible as "syntactic sugar" for more fundamental expressions. That way, there are less syntactic forms for me to define the semantics for.

PHP seems to have a large amount of syntax that can be de-sugared. Some examples:

  • if/endif and other "alternative syntaxes" desugar to if { ... }, etc.

  • for (expr1; expr2; expr3) { statements; } desugars to expr1; while (expr2) { statements; expr3; }.

  • I think the following is true: $foo just means ${'foo'}. That is, referencing a variable by name is just an instance of the more general variable lookup by evaluating an expression to a string.

  • I think this:

    <p>foo</p>
    <?php echo 5; ?>
    <p>bar</p>
    

    desugars to this:

    echo "<p>foo</p>\n";
    echo 5;
    echo "<p>bar</p>\n";
    

    Or in general, ?>blah<?php just means echo 'blah';.

There are certainly many, many other cases like this. I'd like to come up with a list that is comprehensive and confirmed to be accurate. (And any of my examples could be inaccurate, so please correct me!)

1

There are 1 answers

4
Ja͢ck On

That way, there are less syntactic forms for me to define the semantics for.

I think you're approaching this from the wrong angle. Let's start with an example:

$words = array('hello', 'wonderful', 'world');
foreach ($words as $word) {
    echo $word;
}

Nice, but that's too high level; let's replace foreach with a simpler for because our array is not associative:

for ($i = 0; $i < count($words); ++$i) {
    echo $words[$i];
}

Now drop the for:

$i = 0;
while ($i < count($words) {
    echo $words[$i];
    ++$i;
}

That while is kind of annoying:

function doPrint($words, $i = 0)
{
    if ($i < count($words)) {
        echo $words[$i];
    }
    doPrint($words, $i + 1);
}

doPrint($words);

Do we really have to use a function?

echo $words[0];
echo $words[1];
echo $words[2];

What's up with those variables?

echo "hellowonderfulworld";

Bottom line

Don't try to break down a language down to the basics; expressiveness in a language is there for a reason, to be used in the right situation. Learn the basics first and then learn as many "sugars" as you can.

In order to be fluent in a language, you should at least have tried a large majority of what the language has to offer. Practice, practice, practice!