PHP Functions

Functions are used to create a block of code, that we want to run multiple times. Creating a Function allows us to call this Function anywhere in the script. Take some time to learn :-)

2272 views

Edited: 2021-11-30 01:45

PHP functions

A Function is a block of code that can be called elsewhere in a script. In an Object Orientated context, a function that belongs to a class is also known as a mothod. In this article you will learn how to make your own user-made functions in PHP.

A simple user-created function might look like this:

function say_hallo() {
  echo 'Hallo World';
  exit();
}

The exit(); part is used to stop script-execution; without this, the function would just return to the calling location and continue executing the rest of your code. By calling exit(); we will explicitly tell PHP to quit after running the code in the function.

You may call the function like this:

say_hallo();

Instead of outputting the text directly to the output buffer you can also return the text to the calling script. This is very useful when you need to work with the data at the calling location. Here is another example:

echo say_something('This is so cool ^^');

function say_something($what_to_say) {
  return $what_to_say;
  exit();
}

Note that the text to be outputted is provided to the function as an argument, and then accessed within the function via the associated $what_to_say variable.

Note. The order that you define the functions does not matter. This means, you could call the function before defining it, or after having defined it. The reason it still works is that PHP is parses the script before executing it.

Variable scope

Because variables are not global, they will also not be available inside of functions by default, and it is considered a bad practice to make them global. Functions have their own local scope that is inaccessible from the calling location. Instead we can pass the variables on to the function through function arguments when calling it; you already saw a basic example of this in the beginning of the article.

Nevertheless, you may access an outside variable from within a function if you first declare it as global; this is done by using the global keyword inside the function:

$praise = 'Praise be the almighty function, you will praise it, you will.';

function my_praise_func() {
  // Declare the outside variable as global so we can use it inside the function
  global $praise;

  // Output the message
  echo $praise;
  
  // Exit and stop executing
  exit();
}

This is generally a bad practice, so you should instead consider passing the variable in the function by injection technique; injection something into a function is done via the arguments that you define in the function. The below function only has one argument, called $the_message defined:

$the_message = 'Welcome to the website. Please behave yourself.';

welcome_message();

function welcome_message($the_message) {
  echo $the_message;
  exit();
}

If you need to have multiple function arguments, you may add additional ones by separating them with comma:

function welcome_message($the_message, $name_of_user, $age_of_user) {
  $html =  '<p>' . $the_message . '</p>';
  $html .= '<p>Your name is: ' . $name_of_user . '</p>';
  $html .= '<p>And your age is: ' . $age_of_user;
  return $html;
}

There is a couple of things going on in this example that you should know about.

  1. Note how the $html = ... variable is first declared, and then more data added to it with the .= operator. If you leave out the dot, you will instead re-declare the variable, which will overwrite the existent content.
  2. Strings are combined using dots . between strings and variables; this is also known as concatenation.

You can also double quotes around your text strings instead of single quotes and include your variables directly in the string:

$html = "<p>{$the_message}</p>";

When including variables in a string directly, it is a good idea to wrap it in curly brackets to avoid problems with parts of your string getting mixed with your variable name. Finally, you will need to use double quotes, since variables do not work inside of single quotes.

Arguments

Function arguments are also known as function parameters; they can help you "inject" data from a calling location into your function, and, as already discussed earlier in the article, injecting data is better than relying on the global scope.

Functions that are declared in the global scope are going to be available throughout your scripts, even from inside classes, but relying on such global functions is discouraged, because it creates a hidden dependency for the class. If someone was to instantiate the class without knowing about your dependency of an outside-declared function, they might be unable to use the class, typically triggering fetal errors.

Type declarations

When defining your arguments, PHP allows you to restrict the type of the data you allow to be passed to the function by the use of type declarations. If the data consists of "text" and/or special characters, then it is called a string, and if it consists of numbers, it is called an integer — there are also other types, but this is just to give you an example.

To restrict the type of the data of a given variable, you can write the type in front of it, then separate it by a space:

function say_something(string $message) {
}

Why is this useful?

Restricting the type accepted by function arguments is a great way to prevent later mistakes; type checking is relatively new in PHP — in the past we did not have this luxury.

It was quite common for developers to pass on data of the wrong type to functions, and without type checking, the application might just continue running, often leading to very bad errors, data loss, or corrupted data.

Now that we got type checking, PHP will throw an error when the type of the injected data does not match the type expected by the function. It is not hard to see that this helps to more quickly catch problems and correct the errors causing them.

If you passed on an array to an argument that expects a string, PHP would throw you this friendly little error:

PHP Fatal error:  Uncaught TypeError: say_hallo(): Argument #1 ($message) must be of type string, array given, called in ...

You can read more about handling errors here: Creating a Custom Error Handler in PHP

Passing by reference

You may ave noticed that some variables are passed on to a function or class method with an ampersand & in front of the variable; this is known as passing by reference.

function my_beautiful(string &$input) {
  $input = 'My beautiful ' . $input;
}

$person = 'Wife';
my_beautiful($person);

echo $person; // Output: "My beautiful wife"

When a variable is passed by reference, it actually points back to the original data, in the memory; this has a number of side effects that you should be aware of, the most obvious is that when you modify the data from within your function, you will also directly modify the data in the original variable. The benefit is that you do not need to return the modified data from the function (although returning a value can be good practice for other reasons).

When you use this feature right, you can often save memory in your PHP scripts, but in other cases it might actually increase memory usage. I have seen reports about people passing arrays by reference, and it instead resulting in double memory usage. Passing string and integer values should be safe though.

Also objects are always passed by reference, so there is no need to explicitly do it using ampersand & character in front of the function parameter.

A Method is basically a Function

When working with OO PHP you will, no doubt, encounter the "method" term; what is important to remember is that, technically, a "method" is just a "function" that is defined inside a class.

The main difference is in how the method is being accessed. When you define a method in a class, you can also choose to make it either private or public, which basically determines whether the method should be callable from outside of the class.

Classes are a type of blueprint used to create an object, and before you can call a method belonging to a class, you will typically also need to instantiate it. E.g:

$my_new_object = new my_class_name();

When should you create a function?

This is often a subjective decision, but in general, you can create a function whenever you asses that a piece of code is going to be reused elsewhere in your code. If you are just learning PHP, then it is fine to play around with basic functions, but if you have been using PHP for a while, you might want to slowly move over in object orientated territory.

To give you an example from the real world of some code that you would often use from different locations; if you have a chunk of code that you use to connects to a database, then it is going to be easier if you create a function containing the code that you can call whenever needed. Thereby:

  1. You avoid code repetition — this relates to the Don't Repeat Yourself (DRY) principle in programming.
  2. If you need to change the code, you can now update it in one place.

Should you learn Object Orientated PHP?

Once you know how to make functions, you are actually not far away from being able to create your first PHP class and learning object orientated programming. It probably makes it easier to wrap your head around the idea if you just think of a class as being a collection of user made PHP functions that can be called in a similar way to normal functions.

A class is a blue-print of an object. You can instantiate an object in order to use the functions inside (now called methods, because we are in an OOP context).

Modern PHP code often relies heavily on OOP; you do not necessarily need to know everything there is to know, but you should at least learn how to work with code that are distributed in class-form.

Object orientated PHP may seem frighting at first, but it is not really much harder to use than plain old procedural PHP with functions. The main reason why you may find it harder to learn than vanilla PHP is that tutorials and discussions about OOP tend to be very abstract. There are also many tutorials that try to be easier to understand for beginners, some of which you can find in other articles on this website.

Links

  1. User-defined functions - php.net

Tell us what you think:

  1. An in-dept look at the use of headings (h1-h6) and sections in HTML pages.
  2. Pagination can be a confusing thing to get right both practically and programmatically. I have put a lot of thought into this subject, and here I am giving you a few of the ideas I have been working with.
  3. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  4. How to optimize image-loading and automatically include width and height attributes on img elements with PHP.
  5. HTTP headers are not case-sensitive, so we are free to convert them to all-lowercase in our applications.

More in: Web development