I'm learning closures but I'm stuck with this:
function addPrefix($string) {
return function($prefix) use ($string) {
echo $prefix.$string;
};
}
$randomstring = "a test";
$c = addPrefix($randomstring);
echo $c("This is ");
Why is $prefix concatenated? It's not even called as an argument, I just don't get it.
Pay attention in your example there is 2 functions. addPrefix, and an anonymous function it addPrefix returns.
So, $c is this anonymous function (returned by addPrefix), which has the $prefix argument.
Related
How can i set the function as a variable in php
Similar to list function
example: list($x,$y)=array(1,2); // this is okey ,but...
How do I create such a structure?
You are talking about variable function that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
Here is the little example from PHP manual Variable Functions
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
and the other scenario is Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>
The list() function is used to assign values to a list of variables. Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.
What is an anonymous function in PHP? Could you give me a simple example, please?
PHP.net has a manual page about Anonymous functions and on Wikipedia you can read about Anonymous functions in general.
Anonymous functions can be used to contain functionality that need not be named and possibly for short-term use. Some notable examples include closures.
Example from PHP.net
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
PHP 4.0.1 to 5.3
$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
PHP 5.3
$x = 3;
$func = function($z) { return $z *= 2; };
echo $func($x); // prints 6
PHP 5.3 does support closures but the variables must be explicitly indicated
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
Examples taken from Wikipedia and php.net
The first results from Google gives you the answer:
http://php.net/manual/de/functions.anonymous.php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
That you use a function as a parameter (in this example) is an "anonymous function". Anonymous since you don't declare the function explicit like "normally" do it.
function foo($match) {
return strtoupper($match[1]);
}
I have a body function and a function called within the first one.
As can be seen below I don't change the parameters name while using in the second function.
Is it necessary to change the params names for use inside _display_bar();? What are the side effects if I don't?
function main_func($form, &$form_state, $key, $code) {
$output = '';
...
$output .= _display_navbar($trans, $status_names);
return $output
}
function _display_navbar($trans, $status_names) {
$trans = 'bla';
$status_names = 'another bla';
$bar = $trans . ':' .$status_names;
return $bar;
};
Variables have function scope. Unless you specifically declare otherwise, the names are only valid inside the function. They do not bleed into other scopes. There are no side effects. You don't need to use unique names.
It actually does not matter. But you better should not have the same names - it is confusing. Let me give you an example. $s will have 3 after the first function call to sum; 7 after the second function call to sum. The parameters did not have the same name as the function parameter names.
To answer your question fully - there are absolutely no side effects.
function main()
{
$a = 1;
$b = 2;
$s = sum($a, $b);
$d = 3;
$e = 4;
$s = sum($d, $e);
}
function sum($first, $second)
{
$ret = $first + $second;
return $ret;
}
Once a variable is passed to a function, the name of the variable is not important. Only the data is passed through. So your function could be this:
function _display_navbar($foo, $bar) {
$foo = 'bla';
return $bar;
}
And it will return what ever was passed as the second parameter regardless of what the variable name was.
The names you pass as function arguments must be in scope at the point they are called.
It doesn't matter if they have the same name as the formal function parameters, but you must recognise that just because they have the same name doesn't mean that brings them into scope.
So, in your code:
function main_func($form, &$form_state, $key, $code) {
$output = '';
...
$output .= _display_navbar($trans, $status_names);
the last line will be incorrect, unless $trans and $status_names are in scope at the time.
I have an anonymous function which is supposed to call itself. However, I have no variable or function name at hand, so I was hoping to find a function that could do return "this" in context of functions. Is there such a thing?
Here's an example:
$f = function() use($bar, $foo) {
// call this function again.
};
Calling like this:
call_user_func(__FUNCTION__);
Leads to this:
Warning: call_user_func() expects parameter 1 to be a valid callback,
function '{closure}' not found or invalid function name
If I try to put $f in the use-list, then it says the variable is not defined (because it is not yet).
__FUNCTION__ cannot be used in anonymous functions
Pass the variable holding the anonymous function as a reference in the 'use' clause....
$f = function() use($bar, $foo, &$f) {
$f();
};
Tip of the hat to this answer.
Okay, I found out the way to do this:
$f = function() use(&$f) {
$f();
};
$f();
The key thing is to pass $f as a reference. Thus PHP does not try to pass a value but a reference to a memory slot.
I have an anonymous function which is supposed to call itself.
I prefer to use call_user_func_array(__FUNCTION__, $params); when calling a recursive function.
As your example doesn't have any arguments then i guess call_user_func(__FUNCTION__); would be better suited.
You would expect and hope the following code would work but that would be too easy.
$bar = 10;
$foo = 0;
$f = function() use (&$bar,$foo) {
if($bar){ // condition needed to prevent infinite loop
echo $bar-- . PHP_EOL;
call_user_func(__FUNCTION__); // wont work
}
};
$f();
The __FUNCTION__ "Magic constant" is unavailable to closures so the code needs to be adapted to allow the passing of the function variable. we can make the function available by passing it as a regular argument or via the use statement.
Function passed as argument
$bar = 10;
$foo = 0;
$f = function( $__FUNCTION__ = null ) use (&$bar, $foo) {
if($__FUNCTION__ && $bar){
echo $bar-- . PHP_EOL;
call_user_func( $__FUNCTION__, $__FUNCTION__);
}
};
$f ( $f );
Function passed via use statement
$bar = 10;
$foo = 0;
$__FUNCTION__ = function() use (&$bar, $foo, &$__FUNCTION__) {
if($bar){
echo $bar-- . PHP_EOL;
call_user_func( $__FUNCTION__ );
}
};
$__FUNCTION__();
Working example, click edit-> ideone it! to re-run code.
http://www.php.net/manual/en/language.constants.predefined.php
Edit: Posted before code was given. Of course it doesn't work on anonymous functions.
call_user_func(__FUNCTION__, $param1, $param2);
call_user_func_array(__FUNCTION__, $params);
function i_dont_know() {
call_user_func(__FUNCTION__,$params);
//or
$funcname = __FUNCTION__;
$funcname($params);
}
What is an anonymous function in PHP? Could you give me a simple example, please?
PHP.net has a manual page about Anonymous functions and on Wikipedia you can read about Anonymous functions in general.
Anonymous functions can be used to contain functionality that need not be named and possibly for short-term use. Some notable examples include closures.
Example from PHP.net
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
PHP 4.0.1 to 5.3
$foo = create_function('$x', 'return $x*$x;');
$bar = create_function("\$x", "return \$x*\$x;");
echo $foo(10);
PHP 5.3
$x = 3;
$func = function($z) { return $z *= 2; };
echo $func($x); // prints 6
PHP 5.3 does support closures but the variables must be explicitly indicated
$x = 3;
$func = function() use(&$x) { $x *= 2; };
$func();
echo $x; // prints 6
Examples taken from Wikipedia and php.net
The first results from Google gives you the answer:
http://php.net/manual/de/functions.anonymous.php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
That you use a function as a parameter (in this example) is an "anonymous function". Anonymous since you don't declare the function explicit like "normally" do it.
function foo($match) {
return strtoupper($match[1]);
}