0

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?

Average Joe
  • 4,521
  • 9
  • 53
  • 81

3 Answers3

1

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

At least at the view part,

My name is <?php echo $myName ?> and I am <?php echo $myAge ?> years of age.

is better than

<?php echo "My name is $myName and I am  $myage years of age." ?>

It is better to only leave the dynamic part to PHP.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

Both samples can be written in PHP as well:

My name is <?php echo $myName; ?> and I am <?php echo $myage; ?> years of age.

and

<?php echo 'My name is ' . $myName . ' and I am ' . $myage . ' years of age.' ?>

The former uses more time (insignificant) to parse as it goes in and out of PHP, however, the latter is less maintainable from a design point of view. I would suggest the first method to specifically state what's dynamic/PHP and what's not.

If you have short-open-tags enabled in PHP, though it doesn't help with speed any, it may be even easier to read by shortening the first line to the following (my personal opinion):

My name is <?=$myName;?> and I am <?=$myage;?> years of age.
newfurniturey
  • 37,556
  • 9
  • 94
  • 102