Broad Network


PHP Callback Function Coding

PHP Functions with Security Considerations - Part 5

Foreword: In this part of the series I explain how to code callback function in PHP.

By: Chrysanthus Date Published: 12 Nov 2018

Introduction

This is part 5 of my series, PHP Functions with Security Considerations. In this part of the series I explain how to code callback function in PHP. You should have read the previous parts of the series, before coming here, as this is the continuation.

Variable Functions
PHP allows more than one variable to have the same function code. Try the following code:

<?php

    $var1 = 'fn';
    $var2 = 'fn';

    function fn()
        {
             $str = "I am not sure of which variable I belong to.<br>";

             echo $str;
        }

    $var1();
    $var2();

?>

The output is:

    I am not sure of which variable I belong to.
    I am not sure of which variable I belong to.

Here, each function name begins with the $ sign. You simply assign a string whose content is the name of a defined function, to different variables. In the function calls, these variables take parentheses and can also take arguments. Note that the real function has to be defined.

So, PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement functions as values for the array, function tables, and so forth - see later.

Using Variable Function as Value for the Array Element
Try the following code:

<?php

    $arr = array(
                                 'Apple' => "purple",
                                 'Banana' => "yellow",
                                 'Pear' => "green",
                                 'Lemon' => "green"
                             );

    function yellow($a)
        {
             $str = $a . " I am not sure of which key I belong to.<br>";

             echo $str;
        }

    echo $arr['Banana']('Well,');

?>

The output is:

    Well, I am not sure of which key I belong to.

Anonymous Function
The anonymous function scheme allows the same function code to be assigned to different variables. This sounds similar to the above but uses a more secure approach (see below). For the function calls, the variables take parentheses and can also take arguments. Try the following code:

<?php

    $var1 = function()
                {
                     $str = "I am not sure of which variable I belong to.<br>";

                     echo $str;
                };

    $var2 = function()
                {
                     $str = "I am not sure of which variable I belong to.<br>";

                     echo $str;
                };

    $var1();
    $var2();

?>

In the function code, you omit the function name; then assign the whole code to a variable. You must end the function code with a semicolon. The output is:

    I am not sure of which variable I belong to.
    I am not sure of which variable I belong to.

Using Anonymous Function as Value for the Array Element
Try the following code:

<?php

    $arr = array(
                         'Apple' => "purple",
                         'Banana' => function ($a)
                                {
                                     $str = $a . " I am not sure of which key I belong to.<br>";

                                     echo $str;
                                },
                         'Pear' => "green",
                         'Lemon' => "green"
                     );



    echo $arr['Banana']('Well,');

?>

If the function definition is not at the end of the array, then you have to end it with a comma, like the other array values. The output is:

    Well, I am not sure of which key I belong to.

Callback

In a callback function scheme, there are two functions: the main function and a smaller function, which is the callback function. In the body of the main function, certain values become arguments to the callback function. The callback function is actually executed when the main function is called. The body of the callback function is coded in the call of the main function.

Read and try the following code:

<?php

    function mainfn ($variabl, $cb)
        {
            $str= 'We are learning.';
            $colorArr = ['blue', 'green', 'red'];

            $cb($str, $colorArr);
        }

    mainfn('dummy', function ($stri, $arr)
        {
            echo $stri, '<br>';
            echo $arr[1], '<br>';
        });

?>

The name of the callback function is $cb. It is defined in the call of the main function. In the call of the main function, the argument, 'dummy' and its corresponding parameter, $variabl are for the main function.

The callback function is defined in the call of the main function, but called in the definition of the main function. Above, the arguments of the callback function are developed inside the definition of the main function. The arguments are $str and $colorArr.

Note that the second code segment is a statement call; so it ends with a semicolon.

The output is:

    We are learning.
    green

Security Consideration

Problem of Replacing One Argument Type with Another
Different types of values can be for the same argument. This can lead to wrong results. Try the following code, where the second argument to the main function was intended to be a callback, but was accidentally coded as a string with a variable that expands:

<?php

    function mainfn ($variabl, $cb)
        {
            $str= 'We are learning.';
            $colorArr = ['blue', 'green', 'red'];

            echo $cb;
        }

    $var = 'John';

    mainfn('dummy', "Mr. $var is here.");

?>

This kind of problem is rare, but it can still occur.

The output is:

    Mr. John is here.

The callback variable type is now called, callable. You can prevent the above problem with argument type declaration as follows:

<?php

    function mainfn ($variabl, callable $cb)
        {
            $str= 'We are learning.';
            $colorArr = ['blue', 'green', 'red'];

            echo $cb;
        }

    $var = 'John';

    mainfn('dummy', "Mr. $var is here.");

?>

Note the use of the type, callable. I tried the code and I had a fatal error. The program stopped running and prevented wrong results.

Now try the following code, where $cb is actually a callback and the type callable has been used:

<?php

    function mainfn ($variabl, callable $cb)
        {
            $str= 'We are learning.';
            $colorArr = ['blue', 'green', 'red'];

            $cb($str, $colorArr);
        }

    mainfn('dummy', function ($stri, $arr)
        {
            echo $stri, '<br>';
            echo $arr[1], '<br>';
        });

?>

The output is:

    We are learning.
    green

Everything worked fine with type declaration enforced.

That is it for this part of the series. We take a break here and continue in the next part.

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

BACK NEXT

Comments