Skip to main content

PHP Functions

Functions are reusable blocks of code that perform specific tasks.

Instead of writing the same code repeatedly, we can place it inside a function and call it whenever needed.

Functions are one of the most important concepts in programming.


Why Use Functions?

Functions provide:

✅ Code Reusability

✅ Better Organization

✅ Easier Maintenance

✅ Cleaner Architecture

✅ Better Testing

✅ Reduced Bugs


Without Functions

echo "Welcome Aayan";
echo "Welcome Steve";
echo "Welcome Alex";

With Functions

function welcome(string $name): void {
echo "Welcome {$name}";
}

welcome("Aayan");
welcome("Steve");
welcome("Alex");

Function Syntax

function functionName() {

}

Example:

function hello() {
echo "Hello World";
}

Calling:

hello();

Output:

Hello World

Function Declaration

function greet() {
echo "Hello";
}

Function Invocation

greet();

Function Parameters

Parameters allow us to pass data.

Example:

function greet($name) {
echo "Hello {$name}";
}

greet("Aayan");

Output:

Hello Aayan

Multiple Parameters

function add(
$a,
$b
) {
echo $a + $b;
}

add(10, 5);

Output:

15

Typed Parameters

Modern PHP supports strict typing.

function add(
int $a,
int $b
) {
return $a + $b;
}

Return Values

Functions can return values.

Example:

function square(
int $number
) {

return $number * $number;

}

echo square(5);

Output:

25

Void Functions

A function that returns nothing.

function sendMessage(): void {

echo "Hello";

}

Return Type Declarations

function getName(): string {

return "Aayan";

}

Integer Return

function getAge(): int {

return 18;

}

Boolean Return

function isOnline(): bool {

return true;

}

Nullable Return Types

function getPlayer():
?string {

return null;

}

Union Types

PHP 8+

function getData():
string|int {

return "Hello";

}

Default Parameters

function greet(
string $name = "Guest"
) {

echo "Hello {$name}";

}

Calling:

greet();

Output:

Hello Guest

Named Arguments

PHP 8+

function createUser(
string $name,
int $age
) {

}

Calling:

createUser(
age: 18,
name: "Aayan"
);

Variable Number of Arguments

function sum(
...$numbers
) {

return array_sum(
$numbers
);

}

Example:

sum(1,2,3,4);

Output:

10

Variadic Parameters

function broadcast(
string ...$players
) {

}

Pass By Value

Default behavior.

function test(
int $x
) {

$x++;

}

$a = 5;

test($a);

echo $a;

Output:

5

Pass By Reference

function increase(
int &$x
) {

$x++;

}

Example:

$a = 5;

increase($a);

echo $a;

Output:

6

Anonymous Functions

Functions without names.

$hello = function() {

echo "Hello";

};

$hello();

Closures

Closures can access outer variables.

$name = "Aayan";

$fn = function() use (
$name
) {

echo $name;

};

$fn();

Arrow Functions

PHP 7.4+

$add =
fn($a, $b)
=> $a + $b;

Recursive Functions

Functions calling themselves.


Factorial Example

function factorial(
int $n
): int {

if ($n <= 1) {
return 1;
}

return $n *
factorial(
$n - 1
);
}

Function Scope

Variables inside functions are local.

function test() {

$name = "Aayan";

}

Outside:

echo $name;

Produces:

Undefined Variable

Global Variables

$name = "Aayan";

function test() {

global $name;

echo $name;

}

Static Variables

Static variables preserve values.

function counter() {

static $count = 0;

$count++;

echo $count;

}

Calling:

counter();
counter();
counter();

Output:

123

Function Existence

function_exists(
"hello"
);

Callable Type

function execute(
callable $callback
) {

$callback();

}

Callback Example

execute(
function() {

echo "Executed";

}
);

First Class Callables

PHP 8.1+

$fn = strlen(...);

Internal PHP Functions

PHP already provides thousands of functions.

Examples:

strlen()
count()
explode()
implode()
array_map()
json_encode()

Real World Example


Sending Messages

function sendPrefix(
Player $player,
string $message
): void {

$player->sendMessage(
"§6Zyro §8» §f" .
$message
);

}

Economy Example

function addMoney(
string $player,
float $amount
): void {

}

API Example

function jsonResponse(
array $data
): string {

return json_encode(
$data
);

}

PocketMine Example

public function onEnable():
void {

$this->loadConfigs();

$this->registerCommands();

}

Why Functions Matter in PMMP

PocketMine heavily uses functions:

  • Event Listeners
  • Commands
  • Async Tasks
  • Packet Handlers
  • Utilities
  • Database Methods

Common Mistakes


Missing Return

function test():

int {

}

Produces:

TypeError

Wrong Types

function add(
int $a
) {

}

add("hello");

Too Many Parameters

function createPlayer(
$a,
$b,
$c,
$d,
$e,
$f,
$g
)

Consider using objects instead.


Best Practices

✅ Always use type declarations.

function getName():
string

✅ Prefer small functions.


✅ One function should do one thing.


✅ Use meaningful names.

Good:

calculateDamage()
savePlayerData()
broadcastMessage()

Bad:

test()
doStuff()
abc()

Exercises


Exercise 1

Create:

function hello()

Exercise 2

Create:

function add(
int $a,
int $b
)

Exercise 3

Create:

function isAdult(
int $age
): bool

Exercise 4

Create:

function factorial(
int $n
)

Mini Project

Create:

registerPlayer()
banPlayer()
sendStaffMessage()
addMoney()
removeMoney()

Challenge

Create a utility class:

MathUtils
StringUtils
PlayerUtils

Implement reusable functions.


Quiz

Which keyword returns a value?

Answer

return


Which symbol passes by reference?

Answer

&


Which PHP version introduced Arrow Functions?

Answer

PHP 7.4


References

Official Documentation:

https://www.php.net/manual/en/functions.user-defined.php

Anonymous Functions:

https://www.php.net/manual/en/functions.anonymous.php

Arrow Functions:

https://www.php.net/manual/en/functions.arrow.php


Next Chapter

➡ PHP Variable Scope