Functions in PHP

In simple terms, a function is a block of code that can be named and called repeatedly. Sometimes a function is also called a subroutine. We are used to the fact that a regular variable can be assigned a number, a string, or an array, and then get it back by referring to the value by the name of the variable. Functions are structured in a similar way. This is also a kind of variable, but instead of a string or a number, it stores a block of code that is called when using this “variable”.

A function is a very powerful code reuse tool. By creating your own function and writing the necessary code there, you can call and use it as many times as necessary. Otherwise, you would have to copy and paste the code snippet every time you need it.

To make our work easier, we can arrange as a function some part of the code that is used several times in the script. Then, instead of copying and pasting this part of the code, it will be enough to just call this function as if we were accessing a variable.

There are two types of functions – built-in and user-defined.

Built-in functions are functions that the creators of the programming language have already written for us, and we can just take them and use them. PHP has thousands of ready-made functions for all occasions!

One of these functions, already very familiar to us, is a function that displays the text passed to it on the screen – print ().

The programmer creates user functions independently. These functions are usually only used within a single project or even script.

Function Anatomy

As with ordinary variables, working with functions consists of declaring and using them.

Before using a new function, you must declare it:


function <function name>(<function argument>) {

    <function body>

    return <function execution result>;


The easiest way to explain all the components of a function is with an example.

Let’s say on our site we want to show whether the year selected by the user is a leap year. To do this, we will write a function into which the year is passed. As a result of the function, we want to get the value “true” if the year is a leap year, and “false” if not.

The definition of such a function:


function is_leap_year($year) {

    if ($year % 4 != 0) {

        return false;


    elseif ($year % 100 == 0) {

        if ($year % 400 == 0) {

            return true;


        else {

            return false;



    else {

        return true;



An example of using the function:


$year = 2034;

if (!is_leap_year($year)) {

    print(“2034 is a simple year”);


else {

    print(“2034 is a leap year”);


You can practice using functions in PHP in this simulator.

Function arguments and scope

Our function is able to calculate whether the given year is a leap year.

It is important to understand that a function is like a program within a program. This means that inside such a function, variables that were defined outside of it will not be available. To pass information from outside to inside a function, you need to use function arguments.

Function arguments are variables that a function can receive from external code. In the is_leap_year example, there was only one such variable – $year.

The arguments are necessary because the function “does not see” variables defined outside its boundaries. Therefore, the necessary variables must be passed to it explicitly.

The reverse is also true – variables defined inside the function will not be accessible from outside. Such variables are called local because they are local to the function.

Unlike arguments, which can be multiple, a function can return only one value to the external code – using the “return” instruction (return). The return value is called the result of the function.

Attaching Files in PHP

PHP has support for calling one script from another. Using a special language construct, you can call a script from a separate file by its name, just as functions are called by name. This ability is called file connection. Moreover, such a file can be either a php script or any other text file. For example, an HTML page.

Why separate and include php scripts

PHP developers split the entire source code of the project into separate scripts to make them easier to work with. If you had to write all the code in one file, then such a scenario would become simply immense and it would become absolutely impossible to navigate there. Therefore, splitting code into different scenarios is a natural way to deal with complexity.

There is another positive effect of such a division. By separating repetitive blocks of code into separate scripts, you can reuse the same code in different files and include it only on demand. A good example is custom functions. It is very convenient to declare them in a separate script, and then include them where these functions are needed.

Ways to connect files

There are two language constructs for including files in PHP: require and require_once. How are they different? In fact, the differences between them are minimal. Both of these keywords include the file with the given name and raise an error if the given file does not exist.

However, the peculiarity of require_once is that the file will be included only once, even if this instruction is called several times with the same file name.

File connection examples

First, let’s see how easy it is to include one script inside another. To do this, we use the require statement. Let’s say we have two scripts: index.php and sub.php.

Sub.php file content:


print(“Hi, I’m content from sub.php!” . PHP_EOL);

The index.php file contains the code that will include the sub.php script:


require ‘sub.php’;

print(“And I’m index.php!” . PHP_EOL);

Fun fact: require can be used as a keyword or as a function.

The result will be the same:


require(‘sub.php’); // use as a function

print(“And I’m index.php!” . PHP_EOL);

Result of work:

Hello, I’m content from sub.php!

And I am index.php!

What happened? Two scripts seemed to stick together into one: all the contents of sub.php were executed and added to the beginning of the index.php script.

How to work with the require function is described in detail in this task.

Absolute and relative paths

When connecting a file, you can specify an absolute or relative path as its address.

An absolute path includes the full address of the file from the root of the drive.

Example: /var/www/web/site/inc/sub.php

A relative path only contains an address relative to the current working directory. So if the script is in the /var/www/web/site folder, then you can use the following path to connect the file: inc/sub.php

Always prefer to use relative paths so that the site will continue to work if it is moved to a different folder.

Useful Constants

PHP has useful built-in constants that come in handy for use in the path of an include file.

__DIR__ – Full path to the directory where the current script is located

__FILE__ – Full path to the current script

Visibility of Variables in Included Scripts

It should be remembered that since connecting files is just gluing them into one, then all variables in different scenarios also receive a common scope.

PHP does not have the module system that exists in other programming languages ​​(Python, Java, ECMAScript 6). It is not possible to “import” only individual variables or functions from an included script.

It also follows from this that if you connect one script twice, then the variables and functions from it will also be declared again, and this may cause an error. So use require_once to prevent this from happening.

Leave a Reply

Your email address will not be published.