Functions in PHP
Functions are central in PHP. We’ll learn about functions with a few different examples.
<?php
// Here's a function that takes two integers and returns
// their sum as an integer.
function plus($a, $b) {
return $a + $b;
}
// In PHP, you can omit the type declarations, but it's
// good practice to include them for clarity and type safety.
function plusPlus(int $a, int $b, int $c): int {
return $a + $b + $c;
}
// The main logic of our script
function main() {
// Call a function just as you'd expect, with name(args).
$res = plus(1, 2);
echo "1+2 = " . $res . "\n";
$res = plusPlus(1, 2, 3);
echo "1+2+3 = " . $res . "\n";
}
// In PHP, we don't need a specific main() function.
// The code outside of functions is executed immediately.
main();
To run the script, save it as functions.php
and use the PHP interpreter:
$ php functions.php
1+2 = 3
1+2+3 = 6
PHP functions are similar to those in many other languages. Here are some key points:
Functions are defined using the
function
keyword followed by the function name and parentheses for parameters.PHP doesn’t require explicit return type declarations, but you can add them (as shown in the
plusPlus
function) for better code clarity and type checking.Unlike some languages, PHP doesn’t require you to declare variable types in function parameters, but it’s often good practice to do so.
PHP doesn’t have a built-in
main()
function that’s automatically called. Instead, code outside of functions is executed immediately when the script is run.To print output, we use
echo
instead of aprint
orprintln
function.
There are several other features to PHP functions. One is returning multiple values using arrays or objects, which we’ll look at in future examples.