Create PHP function that takes function as a parameter - php

I am trying to create a PHP function that takes another PHP function as input. Here is an example:
function getMean(function){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum =+ (function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
}

Perhaps something like this should do it. PHP has a "type" called callback, which can be a closure (as of PHP 5.3), name of a function or array containing object and the method to call. These callbacks can be called with call_user_func()
function getMean($callback){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum =+ (call_user_func($callback, $currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
return $sum;
}

You need PHP 5.3 to do that natively.
function getMean($function){
$allUsers = getAllUsers();
$sum = 0;
foreach ($allUsers as $currentUser ){
$sum += ($function($currentUser['CONSUMER_ID'], 5, 8))/(8-5);
}
return $sum;
}
getMean(function($consumer_id, $five, $eight) {
return $consumer_id;
});
I you run PHP 5.3- (lower than 5.3), you need to use a callback (documentation is here) along with the call_user_func() or call_user_func_array() function.

you can do that as long as function($currentUser['CONSUMER_ID'], 5, 8) returns something

It looks like the PHP Eval function is what you are looking for. Pass the getMean function a string, and then change the line to have $sum =+ (eval($param) .....)
Security is a problem though because any function can be passed.

Save the function as a variable.
$function = function($param1){ //code here }
and pass it to your other function as a parameter.
function getMean($function)
{
//code here
$sum += $function($param);
}
[edit]
PHP.net Manual - Variable Functions

are you searching for anonymous functions?
Felix

If you want to dynamically create a function in php < 5.3 then youre stuck with using create_function. Becuase of how you use this function its really insane to use it for anything but but creating simple function for array_map,array_walk or things that do simple calculations or basic text processing.
If youre doing anything more complex than that its much easier and less of a headache to simply define the function as normal and then use it with call_user_func or call_user_func_array as others have suggested.
DO NOT USE eval :-)

Related

How to avoid a really long list of function parameters in PHP?

My problem is that I have lots of functions with VERY long lists of function parameters such as this one:
function select_items($con,$type,$id_item,$item_timestamp,$item_source_url,$item_type,$item_status,$item_blogged_status,$item_viewcount,$item_language,$item_difficulty,$item_sharecount,$item_pincount,$item_commentcount,$item_mainpage,$item_image_width,$item_image_height,$item_image_color,$item_modtime,$order,$start,$limit,$keyword,$language,$id_author,$id_sub_category,$id_category,$id_tag,$id_user){ ... }
As you can see its super long and (of course) very hard to maintain. Sometimes I need all of the variables to construct a super complex sql query, but sometimes I just use 1 or 2 of them. Is there a way to avoid this colossal list of parameters? For example with some strict / special naming convention ?
So basically I need something like this:
$strictly_the_same_param_name="It's working!";
echo hello($strictly_the_same_param_name);
function hello() //<- no, or flexible list of variables
{
return $strictly_the_same_param_name; // but still able to recognize the incoming value
}
// outputs: It's working!
I thought about using $_GLOBALs / global or $_SESSIONs to solve this problem but it doesn't seems really professional to me. Or is it?
For a first step, as you said, sometimes you need to call the function with only 2 args, you can set default values to your arguments in the declaration of your function. This will allow you to call your function with only 2 args out of 25.
For example:
function foo($mandatory_arg1, $optional_arg = null, $opt_arg2 = "blog_post") {
// do something
}
In a second step, you can use, and especially for that case, arrays, it will be way more simple:
function foo(Array $params) {
// then here test your keys / values
}
In a third step, you can also use Variable-length argument lists (search in the page "..."):
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
But ultimately, I think you should use objects to handle such things ;)
You can try use ... token:
$strictly_the_same_param_name= ["It's working!"];
echo hello($strictly_the_same_param_name);
function hello(...$args) //<- no, or flexible list of variables
{
if ( is_array( $args ) {
$key = array_search( 'What you need', $args );
if ( $key !== false ) {
return $args[$key];
}
}
return 'Default value or something else';
}

Confused on PHP func_num_args() Function

Following a Tutorial I am struggling with an issue in a PHP function. I have some basic background on C# and Java and according to my knowledge this code shouldn't work since I am not passing any parameter in the add() function, but , surprisingly!, it works!
According to PHP Manual the func_num_args() Gets the number of arguments passed to the function.so how we can echo the result of the add() function while we are not passing any parameter in the function?! Also, if the function is for getting the number of arguments how we can use it to calculate the numbers?!
<?php
function add(){
$args = func_num_args();
$sum = 0;
$i = 0;
for($i; $i< $args; $i++ ){
is_int(func_num_args($i)) ? $sum+= func_num_args($i) : die('Use Only Numbers');
}
}
echo add(2,5,10,12);
?>
Thanks for your comments
Use func_get_args():
function add(){
if(!func_num_args())return 0;
$args = func_get_args();
$sum = 0;
foreach($args as $arg){
if(is_int($arg)){
$sum += $arg;
} else {
die('Use Only Numbers');
}
}
return $sum;
}
As I mentioned in comments for "no args" case:
func_num_args()s return value is 0. for-loop in your code will not work as of $i < $args simplifies to 0 < 0, which is false.
To prevet that, you may try to use:
if(!func_num_args()){
die('There are no args!');
}
Your line echo add(); will work anyway, because:
PHP has support for variable-length argument lists in user-defined
functions. This is really quite easy, using the func_num_args(),
func_get_arg(), and func_get_args() functions.
No special syntax is required, and argument lists may still be
explicitly provided with function definitions and will behave as
normal.
Use func_get_args()
func_num_args()s return value is 0. for-loop in your code will not work as of $i < $args simplifies to 0 < 0, which is false.
To prevet that, you may try to use:
if(!func_num_args()){
die('There are no args!');
}
I think you are confused because you know what function overloading is, but php does not support function overloading in this manner.
Please go through this link. It will really help you out of your confusion.
php function overloading

Php writing a function with unknown parameters?

How would I go about writing a function in php with an unknown number of parameters, for example
function echoData (parameter1, parameter2,) {
//do something
}
But when you call the function you can use:
echoData('hello', 'hello2', 'hello3', 'hello'4);
So that more parameters can be sent as the number of parameters will be unknown.
Just for those who found this thread on Google.
In PHP 5.6 and above you can use ... to specify the unknown number of parameters:
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4); // 10
$numbers is an array of arguments.
func_get_args()
function echoData(){
$args = func_get_args();
}
Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted
Similar functions about arguments
func_get_arg()
func_get_args()
func_num_args()
use func_get_args() to retrieve an array of all parameters like that:
$args = func_get_args();
You can then use the array or iterate over it, whatever suits your use-case best.
You can also use an array:
<?php
function example($args = array())
{
if ( isset ( $args["arg1"] ) )
echo "Arg1!";
}
example(array("arg1"=>"val", "arg2"=>"val"));

Pass a function by reference in PHP

Is it possible to pass functions by reference?
Something like this:
function call($func){
$func();
}
function test(){
echo "hello world!";
}
call(test);
I know that you could do 'test', but I don't really want that, as I need to pass the function by reference.
Is the only way to do so via anonymous functions?
Clarification: If you recall from C++, you could pass a function via pointers:
void call(void (*func)(void)){
func();
}
Or in Python:
def call(func):
func()
That's what i'm trying to accomplish.
For what it's worth, how about giving something like this a shot? (Yes, I know it's an anonymous function which was mentioned in the post, but I was disgruntled at the abundance of replies that did not mention closures/function-objects at all so this is mostly a note for people running across this post.)
I don't use PHP, but using a closure appears to work in PHP 5.3 (but not PHP 5.2) as demonstrated here. I am not sure what the limitations, if any, there are. (For all I know the closure will eat your children. You have been warned.)
function doIt ($fn) {
echo "doIt\n";
return $fn();
}
function doMe () {
echo "doMe\n";
}
// I am using a closure here.
// There may be a more clever way to "get the function-object" representing a given
// named function, but I do not know what it is. Again, I *don't use PHP* :-)
echo doIt(function () { doMe(); });
Happy coding.
The problem with call_user_func() is that you're passing the return value of the function called, not the function itself.
I've run into this problem before too and here's the solution I came up with.
function funcRef($func){
return create_function('', "return call_user_func_array('{$func}', func_get_args());");
}
function foo($a, $b, $c){
return sprintf("A:%s B:%s C:%s", $a, $b, $c);
}
$b = funcRef("foo");
echo $b("hello", "world", 123);
//=> A:hello B:world C:123
ideone.com demo
No, functions are not first class values in PHP, they cannot be passed by their name literal (which is what you're asking for). Even anonymous functions or functions created via create_function are passed by an object or string reference.
You can pass a name of a function as string, the name of an object method as (object, string) array or an anonymous function as object. None of these pass pointers or references, they just pass on the name of the function. All of these methods are known as the callback pseudo-type: http://php.net/callback
function func1(){
echo 'echo1 ';
return 'return1';
}
function func2($func){
echo 'echo2 ' . $func();
}
func2('func1');
Result:
echo1 echo2 return1
In PHP 5.4.4 (haven't tested lower or other versions), you can do exactly as you suggested.
Take this as an example:
function test ($func) {
$func('moo');
}
function aFunctionToPass ($str) {
echo $str;
}
test('aFunctionToPass');
The script will echo "moo" as if you called "aFunctionToPass" directly.
A similar pattern of this Javascript first class function:
function add(first, second, callback){
console.log(first+second);
if (callback) callback();
}
function logDone(){
console.log('done');
}
function logDoneAgain(){
console.log('done Again');
}
add(2,3, logDone);
add(3,5, logDoneAgain);
Can be done in PHP (Tested with 5.5.9-1ubuntu on C9 IDE) in the following way:
// first class function
$add = function($first, $second, $callback) {
echo "\n\n". $first+$second . "\n\n";
if ($callback) $callback();
};
function logDone(){
echo "\n\n done \n\n";
}
call_user_func_array($add, array(2, 3, logDone));
call_user_func_array($add, array(3, 6, function(){
echo "\n\n done executing an anonymous function!";
}));
Result: 5 done 9 done executing an anonymous function!
Reference: https://github.com/zenithtekla/unitycloud/commit/873659c46c10c1fe5312f5cde55490490191e168
You can create a reference by assigning the function to a local variable when you declare it:
$test = function() {
echo "hello world!";
};
function call($func){
$func();
}
call($test);
You can say
$fun = 'test';
call($fun);
Instead of call(test);, use call_user_func('test');.
As of PHP 8.1, you can use First-class callables:
call(test(...));
You can even use methods:
call($obj->test(...));
As simple as it is.
It appears a bit unclear why do you want to pass functions by reference? Usually things are passed by reference only when the referenced data needs to be (potentially) modified by the function.
As PHP uses arrays or strings to refer functions, you could just pass an array or a string by reference and that would allow the function reference to be modified.
For example, you could do something like
<?php
$mysort = function($a, b) { return ($a < $b) ? 1 : -1; };
adjust_sort_from_config($mysort); // modifies $mysort
do_something_with_data($mysort);
where
<?php
function load_my_configuration(&$fun)
{
$sort_memory = new ...;
...
$fun = [$sort_memory, "customSort"];
// or simply
$fun = function($a, b) { return (rand(1,10) < 4 ? 1 : -1; };
}
This works because there are three ways to refer to function in PHP via a variable:
$name – the string $name contains the name of the function in global namespace that should be called
array($object, $name) – refers to method called string $name of object $object.
array($class, $name) – refers to static function string $name of class $class.
If I remember correctly, the methods and static functions pointed by these constructs must be public. The "First-class callable syntax" should improve this restriction given recent enough PHP version but it seems to be just some syntactic sugar around Closure::fromCallable().
Anonymous functions work the same behind the scenes. You just don't see the literal random names of those functions anywhere but the reference to an anonymous function is just a value of a variable, too.

PHP: Variable in a function name

I want to trigger a function based on a variable.
function sound_dog() { return 'woof'; }
function sound_cow() { return 'moo'; }
$animal = 'cow';
print sound_{$animal}(); *
The * line is the line that's not correct.
I've done this before, but I can't find it. I'm aware of the potential security problems, etc.
Anyone? Many thanks.
You can do that, but not without interpolating the string first:
$animfunc = 'sound_' . $animal;
print $animfunc();
Or, skip the temporary variable with call_user_func():
call_user_func('sound_' . $animal);
You can do it like this:
$animal = 'cow';
$sounder = "sound_$animal";
print ${sounder}();
However, a much better way would be to use an array:
$sounds = array('dog' => sound_dog, 'cow' => sound_cow);
$animal = 'cow';
print $sounds[$animal]();
One of the advantages of the array method is that when you come back to your code six months later and wonder "gee, where is this sound_cow function used?" you can answer that question with a simple text search instead of having to follow all the logic that creates variable function names on the fly.
http://php.net/manual/en/functions.variable-functions.php
To do your example, you'd do
$animal_function = "sound_$animal";
$animal_function();
You can use curly brackets to build your function name. Not sure of backwards compatibility, but at least PHP 7+ can do it.
Here is my code when using Carbon to add or subtract time based on user chosen type (of 'add' or 'sub'):
$type = $this->date->calculation_type; // 'add' or 'sub'
$result = $this->contactFields[$this->date->{'base_date_field'}]
->{$type.'Years'}( $this->date->{'calculation_years'} )
->{$type.'Months'}( $this->date->{'calculation_months'} )
->{$type.'Weeks'}( $this->date->{'calculation_weeks'} )
->{$type.'Days'}( $this->date->{'calculation_days'} );
The important part here is the {$type.'someString'} sections. This will generate the function name before executing it. So in the first case if the user has chosen 'add', {$type.'Years'} becomes addYears.
For PHP >= 7 you can use this way:
function sound_dog() { return 'woof'; }
function sound_cow() { return 'moo'; }
$animal = 'cow';
print ("sound_$animal")();
You should ask yourself why you need to be doing this, perhaps you need to refactor your code to something like the following:
function animal_sound($type){
$animals=array();
$animals['dog'] = "woof";
$animals['cow'] = "moo";
return $animals[$type];
}
$animal = "cow";
print animal_sound($animal);
You can use $this-> and self:: for class-functions. Example provided below with a function input-parameter.
$var = 'some_class_function';
call_user_func(array($this, $var), $inputValue);
// equivalent to: $this->some_class_function($inputValue);
And yet another solution to what I like to call the dog-cow problem. This will spare a lot of superfluous function names and definitions and is perfect PHP syntax and probably future proof:
$animal = 'cow';
$sounds = [
'dog' => function() { return 'woof'; },
'cow' => function() { return 'moo'; }
];
print ($sounds[$animal])();
and looks a little bit less like trickery as the "string to function names" versions.
JavaScript devs might prefer this one for obvious reasons.
(tested on Windows, PHP 7.4.0 Apache 2.4)

Categories