This question already has answers here:
Why and how do you use anonymous functions in PHP?
(6 answers)
Closed 6 years ago.
what is the benefit of using the anonymous function like this
//anonymous function
$hello = function(){
echo "hello world";
};
$hello();
instead of using a regular function like this
//regular function
function hello()
{
echo "hello world";
}
hello();
In your first example, the benefits are negligible. The real benefit of anonymous functions is when you (as their name suggests), never give them a name, and pass them directly to another function.
The following is in pseudocode, since anonymous functions are a language agnostic concept. Say you have a function like:
function do-after-5-seconds(f) {
sleep(5000);
f();
}
You can then use it like:
do-after-5-seconds(function() {
print("Hello!");
});
There would be very little point in giving the "hello printing function" a name, since it will never be used anywhere else. It's thus given directly to do-after-5-seconds.
This is a petty example, but often you'll have functions that you'll never use again, so there's no point in polluting the namespace by naming them.
What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
$variable = "echo 'example'";
eval ($variable);
I need to run the $variable that has code inside, without using the eval function, I'm using php 7.4. How can I do that?
Hint: I'm also using Laravel 6.x, is there a Laravel function for that as well?
Are you sure you have to do that? If you have only a limited number of possible functions, the safest thing to do is to simply map them, and then separate the wanted function and the arguments in the variable, using an array instead. More on that later.
If you wanted to provide a generic means for calling functions, you could for example:
$cmd = ['printf', 'foo'];
// interpreted as: printf('foo')
$cmd[0]($cmd[1]);
I'm using printf here, since echo is a language statement and not a function, and therefore wouldn't work like this. If you had to echo here, you'd have to make your own echo wrapper function, like function do_echo($str) { echo $str; }, and call that instead.
Or, for more readable code, you could list the array as:
list($func, $arg) = $cmd;
$func($arg);
If you needed multiple arguments, you could use this structure:
$cmd = ['str_replace', ['sub', 'ob', 'subject']];
list($func, $args) = $cmd;
// Interpreted as: str_replace('sub', 'ob', 'subject'):
$result = $func(...$args);
echo $result; // 'object'
Where the arguments listed in the arguments array, unpacked with the splat operator, are in the same order as the target function's arguments.
There are of course only a limited number of useful functions that will directly output anything. Therefore, in the above example we capture the result from $func instead and then echo; this simply to illustrate the basic use of variable functions and arguments.
This approach will however provide unhinged access to any function in your system, and as such shouldn't be used on anything but data/calls from trusted sources (you). Allowing users to provide any commands will open up your system to a world of mischief and misery.
Therefore, my initial recommendation of providing a map of functions. You could:
Have an array with a list of allowed core functions,
Have an array with a list of your custom wrapper functions, or
Check for valid wrapper functions named with a prefix
You could for example implement wrappers as follows:
function do_echo($str) {
echo $str;
}
function do_replace($se, $re, $str) {
// return or echo, up to you:
echo str_replace($se, $re, $str);
}
This would give you control over what's executed, and also whether values are returned or output, etc. pre/post-process. And then iterate your variable commands as follows:
$cmd = ['echo', 'off'];
list($func, $args) = $cmd;
$func = 'do_' . $func; // adding your prefix
if(function_exists($func)) {
// call with array, unpack arguments:
if(is_array($args) {
$func(...$args);
}
// or call with scalar argument:
else {
$func($args); // interpreted as `do_echo('off')
}
}
For an additional layer of insulation, create a class with your custom calls as its methods, instead of polluting the global space with more functions. Ciykd use a public router method that handles no-match cases; calling e.g. Func::code($cmd), where code() returns the do_* methods.
I often do something like this when I need to map user requests to class public methods that return output; named e.g. view_home, view_search etc. and view_default for a fallback for unmatched requests. Handy for quick prototyping, where index.php?view=* => $this->view_*.
If you're stuck with receiving a string command (why?), you can use regex to parse it into something you can pass to functions. Or, if you absolutely trust the data, eval isn't inherently and categorically evil, especially where a work-around would make for a more complex but equally wide back-door to your system. It's just not very elegant and smells of sloppy design.
This is my first question so please be patience.This question may sounds childish but I really want to know that what is a function in programming? How they are defined and how they are called to execute. I am just learning php. I have seen many functions like this
function myfunction () {
--------
--------
}
and another type function like this
function myfunction (some variables) {
------------
------------
}
I want to know what is the difference in between them? Any help and suggestions or any valuable link will be more appreciated. Before down voting this question any comments or any good learning link will be more helpful to me.
Those functions are exactly the same except for what they are provided (in terms of data). The first one requires no variables to be passed to it externally to run.
The second one has variables it does use that are passed from it externally, however, these may not be required as default values can be set for these variables.
A function in programming is used to perform a repetitive task, such as removing underscores from a string and making the first letter of each word a capital.
To define a variable, the simplest way is to do this:
function my_function () {
// Function code here
}
To call this function, you need to make sure it is accessible (e.g. included on the page), you simply do:
my_function();
That will execute the function and potentially return it's results.
You can also pass variables to functions as stated, but I recommend looking up tutorials on PHP functions.
https://www.google.co.uk/search?q=PHP+Functions ... lots of results for you :-)
This explanation is PHP specific, other languages may vary.
This question already has answers here:
PHP call_user_func vs. just calling function
(8 answers)
Closed 6 months ago.
I dont understand the function, call_user_func() in the sense that i get how it works but I'm not sure why its required or in what context to use it in php. As far as I'm concerned why not just call the function instead of calling a function with a function? Thnx!
call_user_func gives PHP the ability to treat methods and functions as quasi first-class citizens. In functional languages like javascript there is no need for these special tools per-se because a function is an object that happens to be callable.
PHP is getting closer to having this sort of notion though, especially with the closure support that came along with PHP5.3. Take a look at the comment I put under #deceze's answer. There are some other tools (namely variable functions, reflection and now closures) that offer the same basic functionality.
The most notable thing about call_user_func though is how it allows you to treat global functions, static classes and objects with a uniform interface. It's probably the closest thing they have to a single interface to invoke functions no matter how they're implemented. Internally the PHP core group of developers is working to homogenize some sort of a 'callable' or 'invokable' interface for the language, I'm sure we'll see a clean offering in PHP5.4 or the next major release.
I've had a couple situations where this was very necessary. For example, when I was creating a project that allowed a user to construct parts of a programming language, the system would wrap the "tag" definition in a function before running it for security reasons. However, in doing this, I can't simply call those functions, because I don't know when I need to call them, or even what the names would be. Enter call_user_func()...
So, I'm sure you're confused right now. Let me explain. What my system did, was take some XML, and convert it into PHP/HTML/JS with PHP. This allowed for rapid creation of GUIs (which was the goal). Take this XML for example:
<window id="login-win" title="Access Restricted" width="310" height="186" layout="accordion" layoutConfig="animate:true">
<panel id="login-panel" title="User Login">
<form id="login-form" title="Credentials">
<textbox id="login-uname" label="Username"/>
<password id="login-pass" label="Password"/>
<submit text="Login"/>
</form>
</panel>
<panel id="login-register" title="Register">
Nothing, you can't register!
</panel>
</window>
Each XML tag would be read, then fed into it's corresponding PHP function. That function would determine what to do for that 1 tag. In order to pull this off, I had files each named after the tag it handled. So, for example, the tag's file was "submit.php". This file's contents would get wrapped in a generated function, something like:
function tag_submit($variables, $parent, $children){
// deal with the data, then echo what is needed
}
This function's name would be stored in an array, with it's associated tag name, with the rest of the generated functions. This makes it so the function is generated once, and only created when needed, saving memory, since I would do a if(func_exists()) call to determine if I needed it or not.
However, since this is all dynamic, and the user may want to add in a new tag, for say, a < date > tag, I needed to use call_user_func() to get things to work. I can't hard-code a function call if I don't know what the name is.
Hope that all made sense. Basically, yes, it is a rarely used function, but it is still very very useful.
Named functions, anonymous functions, static methods, instance methods and objects with an "__invoke" method are collectively known as 'callables'. If I have a callable it should be possible to call it by placing parentheses afterwards "()" (I'll assume it takes no arguments). This works when our callable is stored in a variable, for example:
$f(); // Call $f
However, what if I store a callable in an object property?
$obj = new stdClass;
$obj->my_func = function() {};
$obj->my_func(); // Error: stdClass does not have a "my_func" method
The problem is that PHP's parser is getting confused because the code is ambiguous, it could mean calling a callable property or calling a method. PHP chooses to always treat this kind of code as a method call, so we cannot call callable properties this way. This is why we need 'call_user_func':
call_user_func($obj->my_func); // Calls $obj->my_func
There are other times when PHP doesn't understand the normal parentheses syntax; for example, PHP currently (5.5) doesn't know how to call the return value of another callable:
get_a_callable()(); // Parse error, unexpected "("
call_user_func(get_a_callable()); // Calls the return value of get_a_callable
It's also not currently possible to call a function definion directly, which is useful to work around PHP's lack of "let" statements, for example:
function($x) { echo $x . $x; }('hello'); // Parse error, unexpected "("
call_user_func(function($x) { echo $x . $x; }, 'hello'); // Calls the function
There are also times where it's useful to have function calls /reified/ as the 'call_user_func' function. For example, when using higher-order functions like array_map:
$funcs = [function() { return 'hello'; },
function() { return 'world'; }];
array_map('call_user_func', $funcs); // ['hello', 'world']
It's also useful when we don't know how many parameters will be needed, ie. we can't substitute our own "function($f, $x, $y, ...) { return $f($x, $y, ...); }".
One particularly nice definition is partial application, which only takes a few lines thanks to call_user_func and call_user_func_array:
function partial() {
$args1 = func_get_args(); // $f, $a, $b, $c, ...
return function() use ($args1) {
// Returns $f($a, $b, $c, ..., $d, $e, $f, ...)
$args2 = func_get_args(); // $d, $e, $f, ...
return call_user_func_array('call_user_func',
array_merge($args1, $args2));
};
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's an actual use of variable variables?
i saw the concept of variable variables in php .
that is a variable whose name is contained in another variable .
like this
$name = ’foo’;
$$name = ’bar’;
echo $foo;
// Displays ’bar’
one advantage that i see is , you can create variable names with numbers or lettes which you can not use normally . like this
$name = ’123’;
/* 123 is your variable name, this would normally be invalid. */
$$name = ’456’;
// Again, you assign a value
echo ${’123’};
// Finally, using curly braces you can output ’456’
and also you can call some functions like this
function myFunc() {
echo ’myFunc!’;
}
$f = ’myFunc’;
$f(); // will call myFunc();
and in a book i saw this
Variable variables are a very powerful tool, and should be used with
extreme care, not only because they can make your code difficult to
understand and document, but also because their improper use can lead
to some significant security issues.
The problem i have is if using variable variables in the code can be that dangerous . why are we using it . and is there any major advantages using variable variables in my code , if any what are those advantages .
you can use it in case of not-user-input. Look
function getVar($gid){
$name = "gid".$gid;
global $$name;
$var = $$name;
return $var;
}
It's useful when you have a lot of variables (same start with ending number, etc...) which is probably save
Look at your example:
function myFunc() {
echo ’myFunc!’;
}
$f = ’myFunc’;
$f(); // will call myFunc();
It is powerful: $f can have a value dynamically and the function called based on this value.
At the same time: If the user was given limitless access to $f this could be a security threat
In some MVC Frameworks they use it to run a function which will vary depending on the URL:
http://www.domain.com/thecontroller/theaction
in PHP side they will parse the url, get the second segment which is the name of the function then run it, but how? they will assign to a variable like what you have mentioned:
$toRun = 'theaction';
$toRun();
I've used double and even treble indirect pointers in C, but have never explicitly used variable variables in PHP (but I have used variable functions and classes).
I think it's somehow reassuring that there's more functionality in PHP than I use - and that I can make informed choices about which constructs I do use (I often use explicit references for example).
A nice usage I saw in some framework is using them to access, easier, values passedfrom another script as an array:
$array['test'];
$array['other'];
$array['third_index'];
// or simply $array = array('test','other','third_index');
foreach($array as $k=>$v)
{
$$k = $v;
}
So you could then have $test, $other and $third_index being usable as variables. Pretty handy when dealing with views, for example.
In PHP you have the create_function() function which creates a unique named lambda function like this:
$myFunction = create_function('$foo', 'return $foo;');
$myFunction('bar'); //Returns bar
Is this actually any better (apart from being more easy) then just doing:
do{
$myFunction = 'createdFunction_'.rand();
}
while(function_exists($myFunction));
eval("function $myFunction(\$foo) { return \$foo; }");
$myFunction('bar'); //Returns bar
Is create_function really better? (apart from the fact that it is more easy)
Using eval() will clutter the global function list, create_function() will not, apart from that there's no big difference. However, both methods require writing the function body inside a PHP string which is error-prone and if you were working on my project I would order you to just declare a helper function using the normal syntax.
Anonymous functions in PHP are so poorly implemented that your code is actually better off not using them. (Thankfully this will be fixed in PHP 5.3).
On my understanding of the relevant docs,[1] they both do the same thing, create_function() just comes up with a unique function name for you.
To address some other comments on this question:
create_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is only useful for the given scope.
It may well be that eval() runs in the current scope, but function definitions get dumped into the global namespace anyway.[2] So whenever you define a function, it will be accessible everywhere else in your program.
Using eval() will clutter the global function list, create_function() will not
create_function() only returns a string with the name of the new function,[3] not some special callback type. So, both techniques will pollute your global namespace.
So no, apart from create_function() being easier, it does not appear to be any better than eval().
Footnotes:
[1] http://au2.php.net/manual/en/functions.user-defined.php ; http://au.php.net/create_function ; http://au.php.net/eval
[2] http://au2.php.net/manual/en/functions.user-defined.php
[3] http://au.php.net/create_function
Personally, I've found that create_function() is extremely handy when sorting arrays.
In fact, I just searched the web, and it seems that the PHP documentation has a good example of this.
http://us.php.net/create_function
Scroll down to Example #3 Using anonymous functions as callback functions.
create_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is only useful for the given scope.
(apart from the fact that it is more easy)
I don't understand how you can dismiss this so readily. Given your two examples, which is easier to understand at a glance? Create_function tells you what you intend to accomplish. Eval doesn't.