handkock
handkock

Reputation: 1077

CakePHP: Undefined variable, but it is defined

I am using CakePHP 2.4.4. In the Controller I am setting an array :

$bla = array();
$bla[] = 'phone';
$bla[] = 'id';
$this->set(compact('bla'));

In the view when I try to debug this $bla array it debugs well. But when I try to check if one string is in this array it gives me the Undefined variable: bla error. The whole view's code:

     array_walk_recursive($data, function(&$val, $key) {
        if (is_numeric($val) AND in_array($key, $bla)) { //this line gives me error: Undefined variable $bla, but it is actually defined
            if (ctype_digit($val)) {
                $val= (int) $val;
            } else {
                $val = (float) $val;
            }
        }
    });

Upvotes: 0

Views: 466

Answers (1)

u_mulder
u_mulder

Reputation: 54831

Anonymous function you've created in array_walk_recursive has no access to $bla and any other outer variables. You should explicitly pass this variable to this function with use:

array_walk_recursive($data, function(&$val, $key) use ($bla) {
    if (is_numeric($val) AND in_array($key, $bla)) {
        if (ctype_digit($val)) {
            $val= (int) $val;
        } else {
            $val = (float) $val;
        }
    }
});

Upvotes: 2

Related Questions