Asked  2 Years ago    Answers:  5   Viewed   85 times

I was playing around with anonymous functions in PHP and realized that they don't seem to reach variables outside of them. Is there any way to get around this problem?

Example:

$variable = "nothing";

functionName($someArgument, function() {
  $variable = "something";
});

echo $variable;  //output: "nothing"

This will output "nothing". Is there any way that the anonymous function can access the $variable?

 Answers

3

Yes, use a closure:

functionName($someArgument, function() use(&$variable) {
  $variable = "something";
});

Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using &.

Thursday, November 17, 2022
1

You should use the double-quotes in the first parameter of the glob function.

glob("mov/$context.mov")

or, if you want, use brackets

glob("mov/{$context}.mov")

In this way the variable name will be replaced with the value.

EDIT:
For the other question:
the script with the glob function can be executed multiple times changing the value of the $context variable before the script inclusion. Example:

$context = "word";
include("test.php");

$context = "foo";
include("test.php");
Friday, August 5, 2022
 
1

While you'll get the usual "global variables are bad" crying, here's the basics:

$web = array(); // define the var at the "top level" of the code tree, outside any functions/classes.
function init_web() {
    global $web; // make it visible in the function
    $web['lang'] = 'en'; // make some settings
}

basically, you had it, but hadn't defined the variable outside the function. Just saying 'global' within the function won't magically create one outside the function - it already has to exist before you try to "internalize" it to the function and change/access its contents.

Saturday, November 26, 2022
 
1

You'll need to use the global keyword inside your function. http://php.net/manual/en/language.variables.scope.php

EDIT (embarrassed I overlooked this, thanks to the commenters)

...and store the result somewhere

$var = '1';
function() {
    global $var;
    $var += 1;   //are you sure you want to both change the value of $var
    return $var; //and return the value?
}
Monday, November 14, 2022
 
2

The include() function does not access the file via HTTP, it accesses the file through the OS's own file system. So GET variables are not counted. (as they are not part of the file name).

In layman's terms, the point of include is to "copy/paste" all the contents on one file to another on the file, so that you don't have one gigantic file, but a few smaller, more maintainable ones.

Saturday, October 15, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 

Browse Other Code Languages