user6085320
user6085320

Reputation:

How to pass a value to an anonymous function?

The method below does not work.

$dir = '/web/source/htm/arc.php'

// no routing
$app->get('/', function() {
    return ob(__DIR__ . $dir);
});

In JavaScript, $dir ( of course in JS syntax ) would be accessible by the function, but in PHP it does not seem to work.

I also tried

// no routing
$app->get('/', function($dir) {
    return ob(__DIR__ . $dir);
});

Upvotes: 2

Views: 87

Answers (2)

arc.slate .0
arc.slate .0

Reputation: 428

Anonymous functions are also known as closures in PHP. This is similar to JavaScript closures, except that the enclosed variables are not created automatically.

This saves memory by not implicitly importing variables you do not need.

You must explicitly import these variables using the use keyword.

$app->get('/', function() use ($dir) {
    return ob(__DIR__ . $dir);
});

See here:

http://php.net/manual/en/functions.anonymous.php

Upvotes: 1

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

In PHP variables outside a function are not accessible inside (with the exception of superglobal variables).

In order to get access to variables outside the scope of a function you have to tell the function that it should have access to it. That is done using the use keyword:

$dir = '/web/source/htm/arc.php'

// no routing
$app->get('/', function() use ($dir) {
    return ob(__DIR__ . $dir);
});

Upvotes: 4

Related Questions