Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Undefined variable in a closure

Tags:

php

The following snippet returns a bunch of input fields but I'm unable to set their values because $data is undefined (it being inside a closure).

$row = array_map(function($n) {
    $name = sprintf('point[%0d]', $n+1);
    $value = $data['measurements'][$n];
    return form_input($name, $value, "class='input-mini'");
}, range($i*6, $i*6+5));

I know global variables are not cool. What's the best way to get around this?

like image 896
stef Avatar asked Nov 14 '12 16:11

stef


People also ask

How do I fix undefined variables in PHP?

Fix Notice: Undefined Variable by using isset() Function This notice occurs when you use any variable in your PHP code, which is not set. Solutions: To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.

Why is my variable undefined PHP?

Undefined variable: the variable's definition is not found in the project files, configured include paths, or among the PHP predefined variables. Variable might have not been defined: there are one or more paths to reach the line with the variable usage without defining it.

Does PHP have undefined?

That means the PHP code tries to get the value of the field that no one has defined and thus does not exist. Quite expectedly, it does not work and raises a notice called Undefined Index in PHP.

What is closure function in PHP?

A closure is an anonymous function that can access variables imported from the outside scope without using any global variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is defined. Closures can work around variable scope restrictions in a clean way.


1 Answers

Inheriting variables from the parent scope

$row = array_map(function($n) use ($data) {
    $name = sprintf('point[%0d]', $n+1);
    $value = $data['measurements'][$n];
    return form_input($name, $value, "class='input-mini'");
}, range($i*6, $i*6+5));
like image 72
aykut Avatar answered Sep 29 '22 01:09

aykut