Codectionary / Developer documentation / PHP

PHP Functions & Type Declarations

PHP functions use the function keyword. Parameter and return type declarations can document and enforce the values a function accepts and returns.

Syntax

function add(int $left, int $right): int {
  return $left + $right;
}

Examples

A typed function

A small, runnable example of this syntax.

<?php
function add(int $left, int $right): int {
  return $left + $right;
}

echo add(2, 3);
?>

Best practices

  • Use scalar and object type declarations at boundaries where they make a function contract clearer.
  • Keep examples small while learning, then combine the idea with a real project.

At a glance

Purpose
Server-side web applications
File extension
.php
Runs in
PHP runtime on a server or CLI
Usually used with
HTML, databases and web servers

Specifications & further reading

Related PHP documentation