Functions

View saved

Define a function

Functions are declared with function and called by name.

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

echo add(2, 3), "\n";

Default arguments

Defaults make parameters optional.

function greet(string $name, string $hi = "Hello"): string {
  return "$hi, $name";
}

echo greet("World"), "\n";

Pass by value

Arrays and objects have special semantics; scalars are copied unless you use a reference.

Function tips

  • Declare parameter and return types in modern PHP
  • Return early on invalid input
  • Keep functions small
  • Avoid depending on global variables

Comments

One comment per signed-in account. Comments are saved with this page’s URL.