vit
vit

Reputation: 55

php: Anonymous function and arguments

I have an array of objects (from DB) and need to foreach this one before send to the viewer:

$data['contracts'] = array();

foreach ($contracts as $c) {
    $data['contracts'][] = array(
         'id' => $c->id,
         'num' => $c->num,
         'delay' => function ($c->date_added) {
              ... blablabla ... 
         },
    );
}

This examples returns an error because $c->date_added is uses, as workaround I must define additional variable before foreach loop:

$date_added = $c->date_added;

How can I use properties in anonymous functions without additional variables?

Upvotes: 1

Views: 57

Answers (1)

Alex Tartan
Alex Tartan

Reputation: 6826

This might be easier:

// more stuff
'delay' => function ($c) { 
    $dateAdded = $c->date_added;
    // rest of bla bla bla...
},
// more stuff

Upvotes: 1

Related Questions