Expressions And Operators: Echo

This intrinsic function converts the value of an expression to string (if necessary) and writes the string to standard output. For example:

<?hh // strict

namespace Hack\UserDocumentation\ExpAndOps\Echo\Examples\Basics;

<<__EntryPoint>>
function main(): void {
  $v1 = true;
  $v2 = 123.45;
  echo  '>>' . $v1 . '|' . $v2 . "<<\n";    // outputs ">>1|123<<"

  $v3 = "abc{$v2}xyz";
  echo "$v3\n";
}
Output
>>1|123.45<<
abc123.45xyz

For value substitution in string literals, see $$. For conversion to string, see $$.

echo cannot output an array. However, echo can output the value of an object provided its type defines a __toString method. For example:

<?hh // strict

namespace Hack\UserDocumentation\ExprAndOps\Echo\Examples\Point;

class Point {
  private float $x;
  private float $y;

  public function __construct(num $x = 0, num $y = 0) {
    $this->x = (float)$x;
    $this->y = (float)$y;
  }

  public function __toString(): string {
    return '(' . $this->x . ',' . $this->y . ')';
  }
  // ...
}

<<__EntryPoint>>
function main(): void {
  $p1 = new Point(20.5, 30.33);
  echo $p1 . "\n";  // implicit call to __toString()
}
Output
(20.5,30.33)