10

Some PHP code I look at is littered with "<?php" and "?>" tags depending on whether it's outputting HTML or not. Is there any performance benefit to this rather than using echo to write the HTML? It makes the code extremely hard to read when the code's constantly switching between code and HTML via the "<?php" tag.

Note that I'm not just talking about the occasional switchover. The code I'm currently looking at (the mantis-bt source code) is giving me a headache with the number of times it's switching. Very very hard to read.

I wonder if there's a reason for them doing it like this?

Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27
Dan
  • 5,692
  • 3
  • 35
  • 66
  • 4
    not a performance problem unless you are Facebook. – ahmet alp balkan Jan 13 '11 at 16:06
  • 2
    When the page is mostly HTML, the consensus (by a thin margin anyway) seems to be that heavy use of echo is bad form. On the other hand, if the page does not separate control logic and business logic from display, that too is considered bad form. I have heard anecdotally that the overhead for `echo` is comparable to the overhead of switching in and out of `` blocks, but can't find a reference for you. – RobertB Jan 13 '11 at 16:14
  • regardless weather your facebook you should still listen and learn to the methods that facebook use, along with many other large sites. – RobertPitt Jan 13 '11 at 16:18
  • Unless it's a 2GB php script with millions of occurrences, the speed difference would be difficult to measure. – mario Jan 13 '11 at 16:18
  • The programmer probably didn't know about "echo". Feel lucky... at least you didn't inherit code from a programmer who didn't know you could have more than 1 table in a database :( – JoelFan Jan 13 '11 at 19:07

7 Answers7

17

As far as readability goes, I would rather see:

  <ul>
      <?php foreach ($items as $item): ?>
          <li>
              <a href="<?php esc($item->url)?>">
              <img src="<?php esc($item->icon)?>"/>
              <?php esc($item->text)?>
          </li>
      <?php endforeach; ?>
  </ul>

Than:

   echo "<ul>";
   foreach ($items as $item)
   {
     echo "<li>";
     echo '<a href="'.esc($item->url).'">';
     echo '<img src="'.esc($item->icon).'"/>';
     echo esc($item->text);
     echo '</li>';
   }
   echo "</ul>";

Not only that, but the latter lets your IDE of choice handle the HTML syntax and formatting (telling you, for instance, that the </a> is missing). So, unless there's a lot more going on in-between the short bits of HTML, <?php might be preferable.

EDIT: as for performance, anyone serious about code speed will activate a caching pre-compiler which will boil down both versions to the exact same thing.

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
Victor Nicollet
  • 24,361
  • 4
  • 58
  • 89
  • instead of `` why not `img($item->icon)` – RobertPitt Jan 13 '11 at 16:20
  • @Robert you may want to add an alt text to that thing. – PeeHaa Jan 13 '11 at 16:23
  • then `img($item->icon,"location","alt",array("classes","here"))` it just seems a lot neater and when you get templates from regular users it would abide by your html creation thus reducing invalid html – RobertPitt Jan 13 '11 at 16:26
  • @Robert: new programmers on the project know (hopefully) how `` works, but they might not be familiar with the multiple arguments required for `img()` to add classes, alt-text or other attributes, nor will they be so perceptive during the initial training session to remember that `img()` exists in the first place. tl;dr : KISS. – Victor Nicollet Jan 13 '11 at 16:27
  • Thans for the KISS ha, yea i understand but use CI as an example, where they can specifically enable certain aspects of the application – RobertPitt Jan 13 '11 at 16:30
  • That is a feature requirement that justifies the corresponding sacrifices. I could find similar arguments for PHP outputting XML and having XSLT do the actual formatting, or PHP merely generating static files served by lighttpd or a CDN, or any number of other abstraction layers on top of what is ultimately the generation of some HTML - decide what "too much abstraction" means on a per-project basis. – Victor Nicollet Jan 13 '11 at 16:36
  • I'm going to mark this as the answer, as the only valid reason I've seen mentioned for doing it like this is the IDE's syntax highlighting that you mentioned. – Dan Jan 13 '11 at 17:02
3

No reason whatsoever apart from its beginners scripting, there just trying to get the results to the page without any architectural thinking or planning into the system into the long run.

What you should be doing is splitting your design up away from your logical php code, and the design compilation should be done at the end of the scripts runtime.

if you redesign the application I would certainly advise you to start with a framework because the framework will force bad habits away by its design.

Start with codeigniter and create a simple blog, understand how to connect/insert/select/update with the database, learn how to handle sessions, learn the Controllers and the principles of creating one.

After you have had a decent play about with it start looking at the poorly coded applicatioon from a distance not looking at the code or the design but yet what exactly is it doing, is it fetching results from the database, does it have a user system etc etc.

then start implementing the base layer of the application such as the above, once you have the database designed you can then start building the models to fetch from the database at the point within your application, start creating the basic view files taking samples from the pooorly coded application and recoding them within the new application, keeping in mind the structure and cleanliness of the coding.

Hope this helps you start migrating because I certainly do not advise you continue to work with an application such as that.


@mitch

Event thought you second piece of code is cleaner its still combining your view with the rest of your application where it should be like so:

<html>
    <?php $this->load("segments/head"); ?>
    <body>
         <?php echo $this->wrap("span",$this->link("Some Linke",$this->var("homepage"))) ?>
    </body>
</html>

a dedicated set of methods for the view to prevent it interacting with the main logic, this would be wrapped within an object to prevent the scope and only the object should be able to access the main logic.

RobertPitt
  • 56,863
  • 21
  • 114
  • 161
2

Reason it might be like that is for situations like this:

<?php if($logged_in) { ?>
    <span class="x">Welcome, <?= $_SESSION['user'] ?></span>
    <a href="logout.php">Logout</a>
<?php } ?>

Instead of:

<?php 
   if($logged_in) {
      echo "<span class=\"x\">Welcome, " . $_SESSION['user'] . "</span>";
      echo "<a href=\"logout.php\">Lougout</a>";
   }
?>

There are less escape characters to worry about.

mitch
  • 985
  • 10
  • 12
  • 1
    But in your example, you could have just used a single quote instead of escaping them. – Dan Jan 13 '11 at 16:14
  • 1
    I personally like the top example better as well. If you want to change out your HTML or are given an update from another page, it's easier to drop it in. – Don Jan 13 '11 at 16:15
  • You are right, unless you want interpolated strings. Which I didn't show in my example because you can't access your session variables like that. I will agree with Don, though. PHP will be parsing your text server-side instead of just plain text which PHP will ignore and send straight to the user's browser. – mitch Jan 13 '11 at 16:17
  • 1
    Another suggestion: `echo "Welcome, {$_SESSION['user']}";` That's what double quotes are made for in PHP. – Thai Jan 13 '11 at 16:17
  • Thanks Thai, learning something new still... I have never seen { } used to access your super globals like that. – mitch Jan 13 '11 at 16:20
  • Why not use double quotes? Simple, because you need to escape your output, and you can't do that with double quotes. Where's `htmlspecialchars`? Otherwise this is likely open to XSS... – ircmaxell Jan 13 '11 at 16:24
  • I didn't mean my code sample to be a "best practices" item. I meant it to demonstrate the reasons why people might exclude HTML output from echo and leave outside of PHP tags. – mitch Jan 13 '11 at 16:26
0

While this would not produce any noticeable effects as far as code run time, the idea that this is the only place that "Performance" should be calculated, is ridiculous. Developers cost money. So cleaning this all up IS a performance boost! Your own performance!

So do it.

DampeS8N
  • 3,621
  • 17
  • 20
0

PHP offers some features that are not offered by HTML , such as loops. Thus, if you have to use loops several times in your code, you have to keep switching between php tags and HTML. Moreover, PHP helps you implement session control that is not allowed by HTML. Thus, it is important to embed PHP in HTML

In a nutshell, to use additional features we have to use PHP or some other language

Programmer
  • 6,565
  • 25
  • 78
  • 125
  • I think you're misunderstanding my question. I'm not asking why we use PHP. I'm asking why code that contains a lot of PHP code feels the need to switch to non-PHP constantly just to echo some HTML. Rather than just using the echo command. – Dan Jan 13 '11 at 16:16
0

I don't have statistical data to back this up, but it's my understanding that it's more efficient to "turn off" php to output HTML rather than to use echo""; The reason being that when you run your html through echo tags, you're having PHP parse it out to display, while just putting it in the doc itself will let the browser display it WITHOUT having to have PHP parse it.

When I did ColdFusion development, I remember hearing the same case made for tags.

Don
  • 1,570
  • 4
  • 22
  • 38
0

I prefer to use the <?php and ?> because it is easier to read HTML, but if any loss of performance will be very little. I've written HTML with echo but it's very bad to read and find problems in the HTML.

Cesar
  • 3,519
  • 2
  • 29
  • 43