Ensure that an invariant is satisfied


namespace HH;

function invariant(
  mixed $test,
): void;

If it fails, it calls invariant_violation

This function provides a way to have a variable type checked as a more specific type than it is currently declared. A source transformation in the runtime modifies code that looks like:

invariant(<condition>, 'sprintf format: %s %d', 'string', ...);

... is transformed to be:

  if (!(<condition>)) { // an Exception is thrown
    invariant_violation('sprintf format: %s', 'string', ...);
  // <condition> is known to be true in the code below

See also:


  • mixed $test - The condition you are declaring as an expression of fact.
  • ...$args - Arguments supplied if the condition is not met. This is usually a string, with possible placeholders.