Chapter 7. XHP

XHP (named to resemble XHTML) is a feature of Hack that allows programmers to represent an HTML tree as PHP/Hack objects, by means of embedded XML-like syntax. This eliminates entire classes of bugs as well as a major source of security holes in web apps. It makes UI code cleaner, more maintainable, and more flexible.

Traditionally in PHP, you output web pages in one of two ways—either by using PHP templating within HTML:

<tt>Hello <strong><?= $user_name ?></strong>!</tt>

or by concatenating or interpolating strings:

echo "<tt>Hello <strong>$user_name</strong>!</tt>";

With XHP, the same example looks like this:

echo <tt>Hello <strong>{$user_name}</strong></tt>;

This is a normal echo statement, and there are no quotation marks. The HTML-like syntax is part of the grammar.

XHP is a great foundation for a modern, object-oriented web app UI library. In this chapter, we’ll see why you should use it, how to use it, how to build on top of it, and how to convert a legacy codebase to use it.

Why Use XHP?

XHP can help improve the security and correctness of your UI code, with a variety of ways to prevent you from making common mistakes. It also helps organize your UI code more sanely, by providing an object-oriented interface to your HTML markup.

Runtime Validation

Can you spot the problem with this code?

echo '<div class="section-header">';
echo '<a href="#intro">Intro to <span class="metal">Death Metal</sapn></a>';
echo '</div>';

One of the closing tags is misspelled: ...

Get Hack and HHVM now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.