6

The Hack manual makes it fairly clear how to type-annotate function parameters, function return types, and member variables. However, all of the ways I've tried to type-annotate a global variable or function-local variable result in a syntax error:

string $foo   = "foo";        // unexpected T_VARIABLE
$foo : string = "foo";        // unexpected ':'
string $foo;   $foo = "foo";  // unexpected T_VARIABLE
$foo : string; $foo = "foo";  // unexpected ':'

Are such annotations possible? If it is possible, then what is the correct syntax? If it is not possible, then is this by design or is it something the developers plan to implement? (It certainly would be useful.)

jameshfisher
  • 34,029
  • 31
  • 121
  • 167

1 Answers1

7

It's not possible, and this is by design.

Local variables have their types inferred, and global variables don't get type checked (as they can be changed at any time from anywhere by accesing $_GLOBALS).

If there's a particular page of the documentation that could make this clearer, please click the "File A Documentation Bug" link at the bottom of it, so it can be added.

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
  • Makes sense. So possibly in the future we will be able to annotate local variables, but there are no plans to allow this for global variables because PHP semantics make it difficult to type-check. – jameshfisher Apr 16 '14 at 09:12
  • @jameshfisher It's actually because the type and content of variables in the global scope can be changed at any time from any other class/function/etc. This can be done by accessing `$_GLOBALS`. It's the same reason code in global scope is never passed through HHVM's JIT compiler. – Radu Murzea Apr 16 '14 at 13:27
  • @jameshfisher Any particular reason you would want to annotate local variables? They are inferred by the typechecker so there's no need for the programmer to do so... – Claudiu Apr 17 '14 at 03:56
  • 3
    @Claudiu mostly for clarity. Say, I declare some local variable that is supposed to be of some complex `shape` type: it would be nice, if the initial value doesn't satisfy that type, to get an error at the declaration/initialization, rather than at some point later in the program where I attempt to use that value. – jameshfisher Apr 21 '14 at 21:57
  • Gotcha James, that makes sense. Note that the typechecker will point out the assignment place in the errors though, not just where it error'ed - so for most cases it shouldn't be a problem to identify the culprit. If it's more for documentation purposes for other people reading your code, that's another story :) – Claudiu Apr 21 '14 at 22:53