Function declaration in function in php

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: declare function B inside function A, to use it as a parameter in
                          array_map ().

My problem: I get an error message:

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

+5
source share
4 answers

Try the following:

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

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

        ...
    $ponderationfunc(123);
}
+9
source

As in php 5.3, you can use anonymous functions. Your code will look like this (untested warning code):

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

$ponderation , "undefined".

, use.

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

:

PHP, :

array_map('my_function_name', $my_array);

, :

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

, :

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

:

, - .

, , , , Cannot redefine function my_callback_function, .

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

Callback call:

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));
    }
}
+1
source

All Articles