Is This Ever OK?

September 27th, 2008 @ 11:35 pm
Woah! Hold On A Sec! This post has outlived its shelf life. While it's still here for archive purposes, you should make sure the facts stated herein are still correct.

As a developer I’m often torn between the concept of “it works” and the concept of “it’s right.” This is no less true than in the following example…

<?php

class Foo
{

     public $property;

     public function outputProperty($var = null)
     {

          // Some function processing here.
          ?>

          The value of the property is <?php echo $this->property; ?>
          <!-- html here !-->

          <?php

     }

}

?>

There’s great debate amongst the PHP community about when exiting PHP and printing strict HTML is permissible; this example clearly works (you can test it), but is it right?

In terms of readability, it’s terrible. If you’re in the midst of a class and all of a sudden you’re outputting straight HTML, it can confuse a reader. The best commenting in the world can’t help. Most programs that do code highlighting highlight PHP and echo() statements differently.

But on the other side, if you’re going to do a big long string of PHP, and you want to throw in some javascript, doing this isn’t very practical, especially if you have lots of Javascript and, like me, place your strings in single quotes rather than double quotes.

So what do you think, PHP community? Give me your thoughts.

The original work of Brandon Savage.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

Related posts:

  1. Looking Back: Learning From Old Code
  2. Use Registry To Remember Objects (So You Don’t Have To)

Categories: Best Practices, Web Architecture
Comments:

Anonymous wrote at 9/28/2008 4:14 pm:

While I wouldn’t consider myself someone in a position to tell most people reading this what to do, I think I would pummel my devs if they did this. Partly for readability, partly because it seems off, but mostly because I can be pretty certain that layout and presentation is going to be making its way into your business logic.

One quick solution is to just pull the html out into a new php file and turn it into an include or require. Though even that case you would want to take a serious look at the overall architecture of your site as again you probably have a class trying to do too much.

BrandonSavage.net uses gravatars. Get yours!
Search:
Copyright © 2008 - 2010. All Rights Reserved.