search
HomeBackend DevelopmentPHP TutorialA Look at Hack, the PHP Replacement in HHVM

A Look at Hack, the PHP Replacement in HHVM

A Look at Hack, the PHP Replacement in HHVM

You can use the previously created Vagrant box to run the code snippets from this article.

Key Takeaways

  • Hack, the PHP replacement in HHVM, is a statically typed language, which means you must provide types for all variables in your application. However, Hack uses a “gradual typing” system, where types are only expected in “strict” mode, and even then, Hack is smart enough to infer local variable types.
  • Hack introduces several features that improve upon PHP, including User Attributes, which are Facebook’s implementation of annotations, and XHP, a PHP extension that augments the syntax of the language so that XML document fragments become valid PHP expressions.
  • Despite the advantages of Hack and HHVM, there are still obstacles to their adoption, including the lack of support for PECL extensions and the fact that HHVM is solely backed by Facebook. However, Facebook has a tool that can automatically compile PHP extensions for the HHVM target, and developing an extension for HHVM is reportedly easier than developing for PHP.

Why types ?

In the first part of the article we’ve seen that HACK was actually statically typed. This means that you must provide types for all the variables in your application. As a reminder, PHP is dynamically typed so that you never need to type your variables although you can use type hinting for function arguments.

But wait, does that mean that you have to provide types for every single variable of your application? Not exactly, and we are going to see the details.

Facebook’s codebase is composed of hundreds of millions of lines of code and adding types everywhere before they can switch to HACK would have been a real burden. So they’ve come with “gradual typing”: HACK expects types in “strict” mode only. In non-strict mode types would only be taken in account where they are present.

Entering the strict mode is as easy as switching the HACK start tag from

Even in strict mode you need not to annotate all the variables. That’s because HACK is smart enough to infer local variable types. Type annotations are only ever required for class properties, function arguments and return values. I would otherwise recommend to annotate local variables when it could help the understanding of your code.

Let’s look at an example:

<span><span><?hh // strict
</span></span><span>
</span><span><span>require "/vagrant/www/xhp/php-lib/init.php";
</span></span><span>
</span><span><span>// ...
</span></span><span>
</span><span><span>function add(int $a, int $b): int {
</span></span><span>    <span>return $a + $b;
</span></span><span><span>}
</span></span><span>
</span><span><span>// ERROR(calling "add()" on l.17) : Argument 2 passed to add() must be an
</span></span><span><span>// instance of int, string given
</span></span><span><span>echo <p>add(1, "a") = {add(1, "a")}</p>;
</span></span><span>
</span><span><span>// ERROR(calling "add()" on l.22) : Argument 2 passed to add() must be an
</span></span><span><span>// instance of int, string given
</span></span><span><span>function add_array(array<int> $a): int {
</int></span></span><span>    <span>return array_reduce($a, "add", 0);
</span></span><span><span>}
</span></span><span>
</span><span><span>echo <p>add_array([1, "a"]) = {add_array([1, "a"])}</p>;</span></span></span>

The sample code for this section is located at www/type-checker/index.php and you can see its output by pointing your browser to http://localhost:8080/type-checker/.

The first error message is not surprising: calling add(1, "a") generates an error because add() expects the second argument to be an integer.

The second error message is more unexpected: the error is not generated by calling add_array([1, "a"]). It’s actually the call to add(1, "a") inside of add_array() which generates the error! One could have expected that passing [1, "a"] would trigger an error because it’s not an array.

The thing is that the HHVM runtime check is sparse in order not to impact performance: it doesn’t iterate over objects. At this point you would probably question the usefulness of the HACK type system! But don’t worry, there is an easy answer, the “type checker”: it would catch any type mismatches including the one from the previous example. Don’t look for it in the HHVM repository, it hasn’t been released by Facebook yet.

The type checker is implemented as a server that watches your files for changes. Whenever it detects a change, it will scan the modified file together with its dependencies for errors. The errors are reported real-time so that you do not even have to run the code. It has been designed to work really fast even at FB’s scale.

You should now be convinced that the type system works great, but what are the benefits? It allows catching developer errors in real-time, producing more efficient code: A PHP add() function would first have to check the types of $a and $b (i.e. string, null, …) possibly convert them to numbers and only then perform the addition. Whereas with HACK the add() function above adds two non-null integers which is a very fast operation in assembly language (as generated by the HHVM JIT).

If as a developer you are already using PHP type hinting and PHPDoc annotations, switching to the strict mode should be a no-brainer. Your code will become safer and faster – note that some existing QA tools, like Scrutinizer already use type inference to check your code, though they’re not real-time.

If you use PHP mostly because of its dynamically typed nature then you probably want to stick to the non-strict mode.

User attributes

The use of annotations has dramatically increased in the PHP world during the last years. For those who are not familiar with annotations, they are metadata you can add to classes, interfaces, traits, variables and functions/methods.

The Doctrine ORM has probably been one of the first PHP projects to make an extensive use of annotations. Below is an example of a model configuration from the Doctrine documentation:

<span><span><?hh // strict
</span></span><span>
</span><span><span>require "/vagrant/www/xhp/php-lib/init.php";
</span></span><span>
</span><span><span>// ...
</span></span><span>
</span><span><span>function add(int $a, int $b): int {
</span></span><span>    <span>return $a + $b;
</span></span><span><span>}
</span></span><span>
</span><span><span>// ERROR(calling "add()" on l.17) : Argument 2 passed to add() must be an
</span></span><span><span>// instance of int, string given
</span></span><span><span>echo <p>add(1, "a") = {add(1, "a")}</p>;
</span></span><span>
</span><span><span>// ERROR(calling "add()" on l.22) : Argument 2 passed to add() must be an
</span></span><span><span>// instance of int, string given
</span></span><span><span>function add_array(array<int> $a): int {
</int></span></span><span>    <span>return array_reduce($a, "add", 0);
</span></span><span><span>}
</span></span><span>
</span><span><span>echo <p>add_array([1, "a"]) = {add_array([1, "a"])}</p>;</span></span></span>

PHP, unlike many other languages, has no built-in support for annotations. However, the Doctrine annotation library is widely used to extract metadata from Docblocks. An RFC proposing built-in support for annotations in PHP has been declined back in 2011.

User attributes is the Facebook implementation of annotations. They are enclosed in > and their syntax differs a little from Doctrine annotations:

<span><span><?hh // strict
</span></span><span>
</span><span><span>require "/vagrant/www/xhp/php-lib/init.php";
</span></span><span>
</span><span><span>// ...
</span></span><span>
</span><span><span>function add(int $a, int $b): int {
</span></span><span>    <span>return $a + $b;
</span></span><span><span>}
</span></span><span>
</span><span><span>// ERROR(calling "add()" on l.17) : Argument 2 passed to add() must be an
</span></span><span><span>// instance of int, string given
</span></span><span><span>echo <p>add(1, "a") = {add(1, "a")}</p>;
</span></span><span>
</span><span><span>// ERROR(calling "add()" on l.22) : Argument 2 passed to add() must be an
</span></span><span><span>// instance of int, string given
</span></span><span><span>function add_array(array<int> $a): int {
</int></span></span><span>    <span>return array_reduce($a, "add", 0);
</span></span><span><span>}
</span></span><span>
</span><span><span>echo <p>add_array([1, "a"]) = {add_array([1, "a"])}</p>;</span></span></span>

You should note that the user attributes are, unsurprisingly, accessed from the reflection API. Also note that the support for annotating on class properties is still to be implemented.

The sample code for this section is located at www/attributes/index.php and you can see its output by pointing your browser to http://localhost:8080/attributes/.

XHP

By now you should have a foretaste of what XHP is as we have been using it from the first code example of this article. Let me quote Facebook for a more complete definition “XHP is a PHP extension which augments the syntax of the language such that XML document fragments become valid PHP expressions.”. Note that XHP is available as a PHP extension and that HHVM has native support.

With XHP, you can use

{$hello}

where you would have use "

$hello

" with vanilla PHP. While the previous example is trivial, XHP has more to offer:
  • it would validate your markup so that you can not write invalid HTML – think missing closing tags, typos in parameter names, …
  • it provides some level of contextual escaping – as the engine is aware of what your are rendering, it could escape HTML and attribute values appropriately to prevent XSS attacks,
  • you can write your own tags by extending or wrapping existing tags.

Let’s look at an example:

<span><span><?php </span></span><span><span>/** @Entity */
</span></span><span><span>class Message
</span></span><span><span>{
</span></span><span>    <span>/** @Column(type="integer") */
</span></span><span>    <span>private $id;
</span></span><span>    <span>/** @Column(length=140) */
</span></span><span>    <span>private $text;
</span></span><span>    <span>/** @Column(type="datetime", name="posted_at") */
</span></span><span>    <span>private $postedAt;
</span></span><span><span>}</span></span></span>

The full sample code for this section is located at www/hhxhp/index.php and you can see its output by pointing your browser to http://localhost:8080/hhxhp/.

In this example we start by defining a custom tag that will render a

As we are extending the base :x:element, we should override the render() method to return our custom markup as XHP.

Facebook uses the XHP language as the foundation for its UI library which might eventually get open sourced as well.

Asynchronous code execution

I had plans to write a section about asynchronous code execution after having seen some tests in the HHVM repo. However I was not able to come with a working example. It might be due to my little understanding of the topic or the fact that Facebook has not released all the related code yet. I might write about this once Facebook releases some documentation.

Other features

There are a lot of things about the HHVM ecosystem that were not covered by this article, both because I had to make choices on what to include and because Facebook has not released all the code and documentation yet.

A few things that are worth mentioning are the recent support for FastCGI and the integrated debugger.

Facebook has also showcased “FBIDE”, a web based IDE featuring auto-completion, syntax highlighting, collaborative editing and more. We could expect it to be available at some later time.

External ressources

You can find more information in some talks and slides from the Facebook team that I have used to prepare this article. I first heard of HACK by listening to the “taking PHP seriously” talk from Keith Adams and another great talk from Julien Verlaguet. Sara Golemon’s nice slides were also really helpful to me.

Conclusion

Facebook is committed to provide feature parity with PHP for the HHVM. By the end of last year, HHVM was already able to pass 98.5% of the unit tests for 20 of the most popular PHP frameworks. The situation has slightly improved since then.

As of today the HHVM executes PHP code faster than PHP while consuming less memory. That will be a significant advantage in favor of HHVM when the parity is eventually achieved. On top of that you can start introducing HACK to gain even more performance and improve code safety with the help of the type checker – remember you don’t have to convert your whole code base at once thanks to the gradual typing and the fact that HACK and PHP are inter-operable.

In a few months from now, we can expect more documentation and tooling from Facebook. You could even help by contributing to the project on github, there is also a bounty program in place.

One of the problems reported by the PHP community which is probably a major obstacle for adoption is the lack of support for PECL extensions. To mitigate this, Facebook has a tool that can automatically compile PHP extensions for the HHVM target; the success rate is far from 100% though. The other thing that could help here is that developing an extension for HHVM is much easier than developing for PHP.

The fact that HHVM is backed by Facebook alone, and the need to sign a CLA before contributing to HHVM seem troublesome to others.

I do personally think that a fair amount of competition is a great thing for the future of PHP.

To conclude, I would like to thank the Facebook team for the amazing job they’ve done and to have open-sourced it. If you would like to see more SitePoint articles on HHVM and HACK in the future do not hesitate to suggest topics by adding a comment below.

Frequently Asked Questions (FAQs) about Hack PHP Replacement HHVM

What is Hack PHP Replacement HHVM?

Hack PHP Replacement HHVM, also known as HipHop Virtual Machine, is an open-source virtual machine designed for executing programs written in Hack and PHP. HHVM uses a just-in-time (JIT) compilation approach to achieve superior performance while maintaining the development flexibility that PHP provides.

How does HHVM differ from traditional PHP?

HHVM differs from traditional PHP in its execution. While PHP interprets the code at runtime, HHVM compiles the PHP or Hack code into a high-level bytecode which is then translated into machine code. This process allows for improved performance and efficiency.

What is the Hack programming language?

Hack is a programming language for the HipHop Virtual Machine (HHVM) invented by Facebook. It is a dialect of PHP and includes new features such as static typing, type annotations, and generics, which are not available in traditional PHP.

How does Hack improve upon PHP?

Hack introduces several features that improve upon PHP. It includes static typing, which can prevent potential runtime errors. It also supports asynchronous programming, allowing for more efficient handling of I/O operations. Additionally, Hack includes collections, which are high-performance, strongly-typed data structures.

Is HHVM compatible with all PHP code?

While HHVM aims to be compatible with most PHP code, there may be some differences due to the nature of the JIT compilation process. However, HHVM provides a tool called ‘hhvm-autoload’ which can help in migrating existing PHP code to HHVM.

How does HHVM improve performance?

HHVM improves performance by using a just-in-time (JIT) compilation approach. This means that instead of interpreting PHP code at runtime, HHVM compiles the code into a high-level bytecode which is then translated into machine code. This process allows for faster execution and improved efficiency.

Can I use Hack without HHVM?

No, Hack is a programming language specifically designed for the HipHop Virtual Machine (HHVM). Therefore, to use Hack, you need to have HHVM installed.

Is Hack a statically typed language?

Yes, Hack is a statically typed language. This means that the type of a variable is checked at compile time, which can help prevent potential runtime errors.

What are the benefits of using Hack over PHP?

Hack offers several benefits over PHP, including static typing, asynchronous programming, and collections. These features can help improve code safety, efficiency, and performance.

How can I start using HHVM and Hack?

To start using HHVM and Hack, you need to install HHVM on your system. Once installed, you can write your code in Hack and run it using the HHVM runtime. There are also several resources and tutorials available online to help you get started.

The above is the detailed content of A Look at Hack, the PHP Replacement in HHVM. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool