Broad Network


Basics of PHP Functions

PHP Functions with Security Considerations - Part 1

Foreword: In this tutorial I explain the basics of PHP functions.

By: Chrysanthus Date Published: 12 Nov 2018

Introduction

This is part 1 of my series, PHP Functions with Security Considerations. A Function is a set of statements that perform a specific task. When you will get to writing programs, you will realize that programs are very long. You will also realize that there are groups of statements that will have to be doing the same task in different parts of the code (program). You do not need to type this group of statements in different parts of the code. You can type it once, and then call it (the group) wherever it is needed in the code. In this tutorial I explain the basics of PHP functions.

You should have read the previous series, before reaching here, as this is the continuation.

Defining a Function
The group of statements forms the function, but you need to group them in a particular way. By doing this, we say you are defining the function.

A function definition consists of the following in the order given

- The reserved word, function, followed by space.
- The name of the function.
- A list of parameters to the function, enclosed in parentheses and separated by commas (see below).
- The statements that define the function follow, enclosed in curly braces. The statements in the function can have among them, calls to other functions defined in the current program - see below.

Example
In the following example, a function is defined that will add two numbers, find the square of the sum and then print (display) the result.

    function myFn()
        {
            $num1 = 2;
            $num2 = 3;

             $sum = $num1 + $num2;
             $square = $sum * $sum;

             echo $square;
        }

    myFn();

The function begins with the reserved word, function, then a space and myFn(), then a block of statements.  

The name of the function is myFn. This is followed by parentheses. Then you have the block. In the block, you have the definition and assignment of the two integer (whole) numbers. The third statement in the block sums the two numbers. The fourth statement squares the sum. The last statement displays (prints) the square.

Calling a Function
Execution of statements in any block, {}, begins from top to bottom.

In the above code, below the function definition, you have , “myFn();” ,  without the quotes. This statement calls the function definition with the name, myFn . In other words this statement causes the statements in the function definition to be executed.

You call a function by just typing the name of the function, followed by parentheses, in a statement. The parentheses may have what is called, arguments – see below. In the above code, if the function, myFn is never called, it will not be executed.

myFn is an example of a user defined function, the function you, the user defines.

The expression (e.g. myFn()) that calls a function is called the calling function. The function (definition) called, is called the called function.

The return value and return type
A function can return a value. If a function returns a value, the calling expression e.g. myFn(), can be assigned to a variable. You can then do whatever you want to do with the variable. Consider the following code:

<?php

    function myFn()
        {
            $num1 = 2;
            $num2 = 3;
            
             $sum = $num1 + $num2;
             $square = $sum * $sum;
            
            return $square;
        }

    $result = myFn();

        echo $result;

?>

The return statement is:

            return $square;

A return statement begins with the reserved word, return, followed optionally by an expression. This expression can be just a variable, e.g. $square, as in the above case. All statements must end with a semicolon.

We know that in the myFn function, $square is of type, int (whole number). Now, look at the calling statement below the function definition. The right operand (Right Hand Side) of the statement is a function call (calling function) that calls the function (definition), myFn. This function call returns what was returned by the return statement in the function definition. It is the value of the variable identified by $square that was returned. This return value is assigned as content to the variable, newly defined with the name, $result. You can then use $result in any way you want. The print (echo) statement in the code prints the value of $result, which is the same value as that of $square.

In the first code sample above, the function, myFn does not return anything, and because of that it does not have a return statement. In the second code sample, the function, myFn, returns a value from an integer variable. A function returns the value of a variable, not the variable itself.

Try the above code.

Parameters and Arguments
Now, in the above function you can only deal with two particular numbers, which are 2 and 3. This is a disadvantage. If we create (define) variables and assign values to them outside the function definition, then we can always change the values of the variables, sending the variables to the functions after each change. In this way, we shall be able to deal with many other pairs of numbers. The following example illustrates this:

<?php

    $num1 = 2;
    $num2 = 3;

    function myFn($no1, $no2)
        {
             $sum = $no1 + $no2;
             $square = $sum * $sum;
            
            return $square;
        }

    $result = myFn($num1, $num2);

    echo $result;

?>

This time the variables have been created (defined) and assigned outside the function, myFn. Some other function elsewhere in the program (script) can actually change these values. In the definition of the function, the parentheses now have two variables. Each of these variables represent one number that will be sent by the function call. The two variables are for the two numbers needed. These variables in this position, in the parentheses of the function definition, are called Parameters. The parameters are separated by commas. The parameter variables are used within the function definition (block).

For the function call below the function definition above, the parentheses have two variables. These variables in this position are called arguments. The arguments are separated by commas. These arguments of the function are the variables created outside the function (definition). The arguments to a function call, can also be literals, something like:

    $result = myFn(4, 5);

Read the above code sample again and try it.

It is advisable to always make the variables for the parameters different from the corresponding variables for the arguments. If you do not do this, then while manipulating the parameters within the function (definition), you might change the values of the variables outside the function.

Default Value in Parameter
Imagine that you want a function to be adding two values. One can be changing, but the other one should not change. The one that cannot change is called the default value and it can be coded in the parameter list of the function (definition). Try the following code that illustrates this:

<?php

    function fn($p, $q=20)
        {
            $w = $p + $q;

            echo $w;
        }

    $p = 15;

    fn($p);

?>

You use an initialization for the default value, "$q=20" in the parameter (do not follow that with a semicolon). Note that in the function call (calling function) the argument for the default value is not sent; that is, there is no argument for the default value. If you do not like the value for $q, then in the function call, you should send a second argument as $q.

Passing String to a Function
You pass a string to a function just as you pass a number. A string is in single or double quotes. The following code illustrates this:

<?php

    function strFn($str)
        {
            echo $str;
        }

    strFn("a test");

?>

Second string code sample where the string is a variable, follows:

<?php

    function strFn($str)
        {
            echo $str;
        }

    $myStr = 'a test';
    strFn($myStr);

?>

Try the above code samples.

Positions of Function Definition and Function Call
In the above code samples, the function is defined before it is called. If you code the function call before coding the function definition, the whole code will still work.

Case-Sensitivity of Function Names
You can defined a function with one casing and call it with another casing as long as the spellings are the same. Function names are not case-sensitive.

Security Issues
The different types of values (variables) mentioned in this series so far are: Integer, Float, Boolean, string, null, resource, array, and object.

Remember that the string values '0', "0", '', "" are each equal to false but not identical to false. Null is equal to false, but not identical to false.

1, -1, '1', '-1', 'text' are each equal to true but not identical to true.

When coding functions in PHP, you have to note the type of the value you are sending as argument; you also have to note the type of the value the function is returning. This is to avoid misinterpretation within a function definition and misinterpretation outside the function definition (after returning a value): identity should not be confused for equality.

We have done a lot. We have to take a break. We continue in the next part of the series.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

NEXT

Comments