Home » Php » Declaring a function in a function in php

Declaring a function in a function in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

The code:

public function couts_complets($chantier,$ponderation=100){

    function ponderation($n)
    {
        return($n*$ponderation/100); //this is line 86
    }

            ...

    }

What I’m trying to do: to declare a function B inside a function A in order to use it as a parameter in
array_map().

My problem: I get an error:

Undefined variable: ponderation [APP\Model\Application.php, line 86]

How to&Answers:

Try this:

public function couts_complets($chantier,$ponderation=100){

    $ponderationfunc = function($n) use ($ponderation)
    {
        return($n*$ponderation/100);
    }

        ...
    $ponderationfunc(123);
}

Answer:

As of php 5.3 you can use anonymous functions. Your code would look like this (untested code warning):

public function couts_complets($chantier,$ponderation=100) {
    array_map($chantier, function ($n) use ($ponderation) {
        return($n*$ponderation/100); //this is line 86
    }
}

Answer:

In your current code, $ponderation is not covered by the scope of the function, hence the “undefined” error.

To pass a variable to an “internal” function, use the use statement.

function ponderation($n) use($ponderation) {

Answer:

Using a callback function:

In order to use a function as a parameter in PHP it is enough to pass the function’s name as a string as such:

array_map('my_function_name', $my_array);

If the function is actually a static method in a class you can pass it as a parameter as such:

array_map(array('my_class_name', 'my_method_name'), $my_array);

If the function is actually a non-static method in a class you can pass it as a parameter as such:

array_map(array($my_object, 'my_method_name'), $my_array);

Declaring a callback function:

If you declare in the global space all is good and clear in the world – for everybody.

If you declare it inside another function it will be global but it won’t be defined until the parent function runs for the first time and it will trigger an error Cannot redefine function my_callback_function if you run the parent function again.

If you declare it as a lambda function / anonymous function you will need to specify which of the upper level scope variables it is allowed to see/use.

Calling a callback:

function my_api_function($callback_function) {
    // PHP 5.4:
    $callback_function($parameter1, $parameter2);

    // PHP < 5.3:
    if(is_string($callback_function)) {
        $callback_function($parameter1, $parameter2);
    }
    if(is_array($callback_function)) {
        call_user_func_array($callback_function, array($parameter1, $parameter2));
    }
}