Function with no argument and no return type:
<?hh
// void indicate that a function does not return anything.
function display(): void {
  echo "This is an empty function";
}
Function with some argument and return type:
<?hh
function sum(int $val1, int val2): string {
    return $val1+$val2;
}
Function that can take null argument:
<?hh
function checkName(?string $name): string {
  if ($x === null ) {
    return “No Name”;
  }
  return "Hello". $name;
}
Function that can return null value:
<?hh
function checkValue(int $val): ?string {
  if ($val == 0) {
    return null;
  }
  return "The number is :".$val;
}
Function with mixed type argument:
<?hh
// ‘mixed’ type should be used with function parameters where functionality depends on the type.
function checkType(mixed $xval): string {
  if (is_int($val)) {
    return "Number is :".$x;
  } else if (is_string($val)) {
    return "String is :".$val;
  } else {
    return “Other type”;
  }
}
Function taking class object as argument:
<?hh
class MyClass {}
function show(MyClass $obj): void {
  //Body of function here
}
Function taking Vector as argument:
<?hh
function addVector(Vector $varr): void {
  $sum = 0;
  foreach ($varr as $val) {
    $sum += $v;
  }
  echo “Sum is : “ .$sum;
}
Function taking and returning resource:
<?hh
function getResource(): ?resource {
  // UNSAFE
  return fopen('/dev/null', 'r');
}
function storeResource(resource $x): void {
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.