PHP Classes

Hack Language is All that PHP Should Have Been

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog Hack Language is All ...   Post a comment Post a comment   See comments See comments (17)   Trackbacks (0)  

Author:

Viewers: 599

Last month viewers: 198

Categories: PHP Tutorials, PHP Performance, News, PHP opinions

Facebook developers just released Hack, a language based on PHP that introduces several great enhancements.

Read this article to learn more about Hack features, as well learn about some criteria that you may want to evaluate to decide if you want replace your PHP developments with this new programming language.




Loaded Article

Contents

What is Hack?

What Are the Great New Features of Hack?

Will Hack Kill PHP?

Conclusion


What is Hack?

Hack is a programming language based on PHP just announced by Facebook. The syntax is basically the same but it adds several new features to help improving the quality of the code that you write, as well take advantage of HHVM (HipHop Virtual Machine) to execute the code faster.

Facebook HipHop Virtual Machine HHVM Hack language logo

What Are the Great New Features of Hack?

Hack introduced many new features relatively to the current PHP version. Some of those features were proposed to PHP over time but they were never accepted.

Hack code can be mixed with regular PHP code. The way to distinguish which code is to be processed as PHP or Hack is that PHP sections start with <?php and Hack sections start with <?hh. This allows smooth migration between PHP and Hack code, so you can take advantage of Hack features.

Hack is meant to be run with HHVM. There is a type checking phase that verifies the consistency of code according to Hack new rules.

When mixing PHP with Hack code, the PHP code sections are not checked against the new Hack rules, but regular PHP code can call Hack code and vice-versa because it is all part of the same program.

Some Hack features are for different purposes. Let me highlight some of the features that seem more important. I am grouping the features according to their purposes. Some features are meant for multiple purposes, so they are listed here in different purpose sections.

Notice that this article is being written based on Hack documentation. I wanted to try these features in practice but I was not able to compile it on OpenSuSE 13.1 Linux distribution. Any misunderstandings about the described features may be fixed later if necessary.

Bug Prevention

These are features that when used can allow that buggy code be detected before it is executed.

Type Annotations

Type annotations are like type declarations, except they are optional. If you use the wrong types of values, you will be able to detect when you make a mistake.

<?hh
class MyClass {
  const int MyConst = 0;
  private string $x = '';
  public function increment(int $x): int {
    $y = $x + 1;
    return $y;
  }
}

Nullable Types

Nullable types is an extension of type annotations using a question mark to specify that a value maybe of a certain type or NULL.

<?hh
function check_not_null(?int $x): int {
  if ($x === null) {
    return -1;
  } else {
    return $x;
  }
}

Collections

Collections are objects like array but their elements may be set to be of a specific type, thus allowing to detect attempts to set values to incorrect types due to application bugs.

<?hh
// Like all objects, collections has "reference-like"
// semantics for assignment, parameter passing, and
// foreach.
function foo($v) {
  $v[1] = 7;
}
 
function main() {
  $v1 = Vector {1, 2, 3};
  $v2 = $v1;
  foo($v2);
  var_dump($v1);
  echo "\n";
  foreach ($v1 as $key => $value) {
    echo $key . " => " . $value . "\n";
    if ($key == 0) {
      $v1[2] = 9;
    }
  }
}
 
main();

Performance Optimization

Type Annotations

When using type annotations you are telling the runtime engine that a value is of a specific type, so it can optimize the generated native machine code to treat values of that type and avoid spending CPU time performing needless type conversions.

Collections

Given that collections can hold values of the same type, HHVM can generate native machine code that is optimized for storing and retrieving collection values of the specific type of the collection elements.

Asynchronous Programming

Asynchronous programming allows a script to start multiple tasks that run in parallel. Those tasks are often I/O operations that rely on operations that are run by separate servers or other OS processes like those that perform file access, network access and database access.

Traditionally PHP executes those tasks and waits for them to finish before it returns the control to your script. This is synchronous programming.

Synchronous programming is often a waste of performance because your script could start multiple I/O tasks and have them run in parallel, so the end result of all those tasks would returned faster.

With synchronous programming each task can only be started after the previous task has finished. Imagine a script that collects information from different sites. Each one will hold your script for as much as the servers take to respond.

PHP has limited support for asynchronous programming for some purposes, as I have explained in a past blog article. But it is not as clean and consistent solution as for instance using Node.js.

Hack made asynchronous programming not only something that can be done cleanly, but also a without the pain of callback hell or promises used by JavaScript solutions, as we already commented several times in the Lately in JavaScript podcast.

Hack introduces the await and async keywords to define code that may be executed in parallel. The really good part is that you can use a await statement to suspend the execution of the code that follows that statement until the contained asynchronous code finishes.

This is a very elegant asynchronous programming solution because you do not have to be concerned with callbacks or internal event loops, to make your script hold in a certain position while parallel tasks keep running and do other things. This is definitely my favorite feature of the Hack language.

<?hh

class Foo{}
class Bar {
public function getFoo(): Foo {
  return new Foo();
}
}

async function gen_foo(int $a): Awaitable<?Foo>; {
if ($a === 0) {
  return null;
}

$bar = await gen_bar($a);
if ($bar !== null) {
  return $bar->getFoo();
}

return null;
}

async function gen_bar(int $a): Awaitable<?Bar> {
if ($a === 0) {
  return null;
}

return new Bar();
}


gen_foo(4);

Code Reuse

Generics

Generics are basically code templates. You can define classes that have their names and the definitions of other parts defined using parameters that define types evaluated at instantiation time.

This allows to create different classes that perform the same operations using the same code on classes of different types. This way you do not have to create for instance a class variation to deal with integers and another to deal with floating point numbers.

<?hh
class Box<T> {
  protected T $data;

  public function __construct(T $data) {
    $this->data = $data;
  }

  public function getData(): T {
    return $this->data;
  }
}

Will Hack Kill PHP?

Given that Hack is meant to be a direct replacement of PHP, you may be wondering if Hack will kill PHP. Maybe it is too soon to tell, so I can only give my opinion about what can help or prevent that from happening.

Maybe Not

Hack code is not backwards compatible with PHP

While it is nice that HHVM can run regular PHP code, to take advantage of Hack features you need to migrate your PHP code. This means that once you migrate your PHP code to Hack, it will no longer run on the regular PHP based on Zend Engine.

If you move all your code to Hack and only rely on HHVM to run it, you will be fine. Facebook is doing that to all their code.

But if you are like most of PHP developers that rely on third-party class libraries and frameworks, you need to wait for their developers to decide if they will provide Hack enabled versions of their code.

I do not see class libraries and framework developers migrate their code to HHVM anytime soon because it is a lot more effort to maintain two versions of their code.

HHVM does not not all the platforms and PHP extensions

Facebook invested a lot in HHVM and Hack. Nowadays it supports many PHP extensions but HHVM does not yet build and run smoothly on all platforms.

For instance, about 77% of the PHP developers use Windows on the desktop computers they use to develop their PHP work. HHVM does not support Windows yet. Some developers use virtual machines, but that is not yet something all of them are comfortable with.

Facebook is Scary To Many Developers

Facebook is large company that develops software to address their needs. Although they made their software Open Source, the decision to create a new language based on PHP it is not something they have seemed to ask the opinion from the PHP community.

What if some day in the future they decide to drop Hack and move on to Java, C# or something else? Microsoft owns part of Facebook, so scary thoughts like this are not unusual among the Open Source community.

There are companies like for instance Yahoo that invested a lot in PHP by developing their sites using custom PHP extensions that they created for their needs. Those extensions rely on Zend Engine based PHP. I am not sure if Yahoo would be comfortable depending on Facebook controlled evolution of PHP.

I think Facebook needs to conquer the trust of the PHP community first before it can get serious adoption for HHVM and Hack. One way to gain that trust would be to merge efforts with PHP, but the PHP core developers also need to agree with that possibility.

Maybe Yes

Hack Implement Features that PHP Core Developers have Turned Down

Hack really implements features that many developers want. Some of them have been proposed to PHP core developers. Some proposals have even been formalized as RFCs, but they have been systematically turned down.

The RFC process was indeed an evolution of the PHP core decision process. Before there were RFCs, the discussions were vague and the decisions to embrace a proposed feature did not go through a clear process.

Still the RFC process is very frustrating, not because proposals are refused, but rather because the voting process does not require justification from people that refuse the proposals. This way the proponents are never sure how they can improve the proposals to satisfy the requirements of those that refused them.

It seems there are voters that only vote to refuse proposals. Others seem to vote always to match the votes of other people, probably close friends. This is not helpful. Proponents need explicit feedback from voters that refuse their proposals, or else it is a major waste of time and motivation.

I guess Facebook only created HHVM and Hack to not be at the mercy of PHP core developers. They cannot run their business depending on the mood of PHP core developers and all the politics that influence their decisions.

I think the PHP community is also fed up of PHP core developer politics. Their decision process is not agile and often seems obscure. If PHP core developers do not improve their decision process, I will not be surprised if more and more PHP developers move to HHVM and Hack. Some already moved.

Hack is based on HHVM Dynamic Compilation JIT engine

I have been saying that PHP needs a JIT compiler since at least when the Phalanger project implemented a solution to run PHP code faster with .NET JIT compiler engine.

There was even a Google of Summer of Code project to compile Zend opcode into LLVM assembly.

It is more than time that PHP comes with a built-in JIT compiler. Rasmus Lerdord the PHP creator thinks that may only happen in PHP 7. That means many more years waiting for something the HHVM provides now in a usable form.

I think that many PHP developers will not wait years for PHP 7 to benefit from the performance improvements of a dynamic JIT compiler when they can have it using HHVM, especially now that Hack offers many interesting features that lots of PHP developers would like to use.

Switching their PHP code to Hack is the next logical step for PHP developers that have migrated their sites to HHVM based installation.

Hack Could Support a PHP Backwards Compatible Mode

Currently Hack code is not backwards compatible with PHP code. This means that once you migrate your PHP code to Hack, it will no longer run on Zend Engine based PHP.

A better solution would be if Hack supported an alternative syntax that would be compatible with PHP syntax, for instance putting new keywords inside comments, like for instance, instead of this:

<?hh
class MyClass {
  const int MyConst = 0;
  private string $x = '';
  public function increment(int $x): int {
    $y = $x + 1;
    return $y;
  }
}

It would also support this:

<?php
class MyClass {
  const /*int*/ MyConst = 0;
  private /*string*/ $x = '';
  public function increment(/*int*/ $x) /*: int*/ {
    $y = $x + 1;
    return $y;
  }
}

I am sure this would be a more flexible approach that could be embraced by class libraries and framework developers. The current Hack syntax would also be supported, but a syntax like this would allow other developers to keep writing PHP compatible code that would take advantage of Hack enhancements.

Conclusion

Hack is definitely a somewhat unexpected and great development of PHP. It is an alternative version of PHP that provides new features that many PHP developers wanted.

Given that Facebook is seriously committed to develop Hack further to make it useful to more PHP developers, the question you may be asking is whether you should move to Hack, and if so, when?

What do you think? Post a comment here to tell if you have plans to move to Hack at some point and why.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

11. Language theory is all well and good... - Richard Munroe (2014-03-26 02:32)
Can't see using Hack anytime soon...... - 0 replies
Read the whole comment and replies

10. Interesting but young I think - H Johnson (2014-03-25 20:59)
Hopefully it will spur php a little... - 0 replies
Read the whole comment and replies

3. PHP is not intended to be Java - Gilberto Albino (2014-03-25 12:26)
I can't agree with this title... - 3 replies
Read the whole comment and replies

9. Very nice - Frederik Yssing (2014-03-25 10:12)
Some great new features and approaches.... - 0 replies
Read the whole comment and replies

5. Opinion - Rubens Takiguti Ribeiro (2014-03-25 00:57)
What about pthreads?... - 1 reply
Read the whole comment and replies

2. Gee Whiz - Terry Lipford (2014-03-25 00:57)
Just what the world needs........ - 1 reply
Read the whole comment and replies

4. Looks very nice - Dave Kennard (2014-03-25 00:57)
A good improvement to PHP... - 1 reply
Read the whole comment and replies

8. nice work facebook - Victor C Nwafor (2014-03-24 22:36)
i love what facbook has done.... - 0 replies
Read the whole comment and replies

7. Let's see - danielyulianto (2014-03-24 20:16)
Let's see... - 0 replies
Read the whole comment and replies

6. Annotations and Parallelism - Moisés Márquez Gil (2014-03-24 20:16)
Hack Language is All that PHP Should Have Been... - 0 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog Hack Language is All ...   Post a comment Post a comment   See comments See comments (17)   Trackbacks (0)