phpasp-classiccontext-switching

PHP context switching


From the Classic ASP world, there was that issue of context switching. Context switching is you open PHP tags, you write a little bit of a php code, then you close the tags, you go on with a little bit of HTML and go back to PHP and keep doing these switches quite frequently. In ASP, this style of programming is not recommended there we are advised to minimize it as much as we can.

In other words, instead of writing code like this in ASP

My name is <%response.write myName %> and I am <%response.write myage %> years of age.

we are recommended to write code as follows;

<%response.write "My name is " & myName & " and I am " & myage & " years of age."%>

With the latter, ASP.DLL spends less time parsing the script.

My question is does this concept/issue/worry apply in the PHP world or not?


Solution

  • Well, that's not how PHP works at least. There is no context switching, the file is fully PHP, with anything outside the <?php ?> tags amounting to one static echo statement.

    The amount of parsing time taken is pretty much the same and completely irrelevant if you are using op code cache.

    You may use parsekit to compile different files and see what kind of op codes are generated.

    So this:

    <?php echo "hi"; ?>
    <?php echo "hi"; ?>
    <?php echo "hi"; ?>
    <html>
    

    Is exactly the same as:

    <?php
    echo "hi";
    echo "hi";
    echo "hi";
    echo "<html>";
    ?>
    

    Note that the newlines in the former example are not output, even though they are outside php tags.