Functions in PHP
Functions are central in PHP. We’ll learn about functions with a few different examples.
To run the script, save it as functions.php
and use the PHP interpreter:
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.