Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a function in a function in php

Tags:

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: 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]

like image 397
L. Sanna Avatar asked Aug 07 '12 08:08

L. Sanna


2 Answers

Try this:

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

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

        ...
    $ponderationfunc(123);
}
like image 174
chiborg Avatar answered Sep 30 '22 13:09

chiborg


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
    }
}
like image 20
Maerlyn Avatar answered Sep 30 '22 13:09

Maerlyn