Functions are an essential part of programming. They allow us to
read and write to files, connect to databases, send and retrieve data
to and from remote APIs, manipulate text and images, etc.
The list goes on and on.
On top of all that we can even create our own functions with ease.
And this is where the fun begins.
Using built-in PHP Functions
We've already used PHP's native functions print_r()
and var_dump()
rather excessively in the previous tutorials. Both are functions that
accept a parameter - the value we pass between the parentheses ($parameter)
.
Apart from just doing something, many functions also return one or
more values. An example would be str_replace()
,
which is used to replace parts of a string with something else.
After that it returns the string with the text already replaced.
// str_replace(what to replace, the replacement, the original text)
echo str_replace('great', 'fantastic', 'what a great day!');
what a fantastic day!
We're not gonna dig too deep here for now, since we'll be using dozens of functions in the coming chapters. It's enough for you to understand that functions can return values as well.
Declaring PHP Functions
Alright, moving on to the good part. Let's create our very own function! You'll be surprised how easy it is.
To tell PHP that we want to declare a function, we start with
the keyword function
followed by the name we want to give
the function sayHello
and the parentheses ()
. This part is
called the function header.
After the header we have the body enclosed by curly braces {}
and that's where we gonna make the magic happen.
After declaring the function, we still have to call (use) it in the end. Just like a regular PHP function.
// declare/define the function
function sayHello() {
echo "Well hello there!\n";
}
// call the function
sayHello();
Well hello there!
Not too impressive yet? Let's add a parameter $name
and be more
personal here! By declaring $name in the header, we tell PHP how
we want to address the variable inside our function. We could also
name it $stuff and then refer to it as $stuff within the function body.
function sayHello($name) {
echo "Well hello there $name!\n";
}
sayHello('Bob');
sayHello('Joe');
sayHello('Jen');
Well hello there Bob!
Well hello there Joe!
Well hello there Jen!
If we don't pass a parameter, it will result in a fatal error. Just try it for yourself.
sayHello();
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function sayHello() ...
If we want to make the parameter optional, we can add a default value
in the function header. Let's do it like this ($name = 'Stranger')
and give it a try.
function sayHello($name = 'Stranger') {
echo "Well hello there $name!\n";
}
sayHello('Bob');
sayHello();
Well hello there Bob!
Well hello there Stranger!
Returning Values from Functions
More often than not, we want a function to return something, like
the result of a calculation or database query. To achieve that,
we use the keyword return
followed by what we want to return.
Let's start with a simple example.
function getMyText() {
return "Look at this amazing text!\nIt came from a function!\n";
}
echo getMyText();
Look at this amazing text!
It came from a function!
In this example we're just blindly returning a predefined text and pass the returned value to echo. It's really that simple to return a value. Now let's be a little more fancy and give our function some parameters to calculate something.
function calculateTaxFromNetPriceAndTaxRate($netPrice, $taxRate) {
return $netPrice / 100 * $taxRate;
}
echo calculateTaxFromNetPriceAndTaxRate(50, 20.0);
10
Parameter and Return Types in PHP 7
Starting from PHP version 7 we can be more specific and declare
what primitive (scalar) type of value has to be passed to our
function and what type it will return.
All we have to do is to change our function header a little bit from
functionName($value)
into this
functionName(float $value): float
.
By the way - since our function header is becoming a bit longer, we can simply format it differently. The behavior will still be the same - PHP does not care about formatting at all.
function calculateTaxFromNetPriceAndTaxRate(
float $netPrice,
float $taxRate
): float {
return $netPrice / 100 * $taxRate;
}
echo calculateTaxFromNetPriceAndTaxRate(50, 20.0);
10
Functions and Scope
Functions live in their own little world to some extent.
For example - they don't know about any of the variables outside.
The example below results in a Notice
from PHP, telling us that
the variable name
is not defined.
function sayHello() {
echo $name;
}
$name = 'Bob';
sayHello();
PHP Notice: Undefined variable: name in ...
While there are ways to make variables accessible inside of the function, we won't go into the details here. It's rarely a good idea and often the source of disaster. Just pass the variables you want to use inside a function as arguments to said function.
Pass by Value vs Reference
There are essentially two different ways to pass values to a function. The first way is called "pass by value", which is what we've been doing until now. If we pass a variable to the function, the value is actually copied into the function. Let's look at the example to see what that actually does.
function changeName($name) {
$name = 'Harry';
echo "Inside the function the name is now $name\n";
}
$name = 'Bob';
changeName($name);
echo "Outside of the function the name is still $name\n";
Inside the function the name is now Harry
Outside of the function the name is still Bob
See - although we changed the value of $name to Harry, it does not affect the original variable outside of the function.
If we want to change the value of the variable outside of the function
scope, we need to add a little extra to our function header.
The magic bit to do this is the &
sign and we add it like so
function changeName(&$name)
right in front of the parameter.
This is called "pass by reference". It tells PHP that we dont want to pass the actual value to our function. Instead we want PHP to "look" for the variable $name and we're just giving directions. Let's check our modified example again.
function changeName(&$name) {
$name = 'Harry';
echo "Inside the function the name is now $name\n";
}
$name = 'Bob';
changeName($name);
echo "Outside of the function the name is now $name as well\n";
Inside the function the name is now Harry
Outside of the function the name is now Harry as well
Ok - you probably have somewhat of a headache by now so we're gonna leave it at that. If you actually managed to follow and grasp the whole tutorial. Impressive! Your comprehension ability is leagues beyond mine!
previous : : For Foreach And While Loops In Phpnext : : Interactive Console Dice Game