Here's my problem, I'd like to have a string that would define my function parameters like this :
function blabla($param1, $param2){
my cool code . $param1 . $param2;
}
$params = 'param1, param2';
blabla($params);
The problem is that when I do this, he uses the string 'param1, param2' as ONE arguments instead of TWO like i'd want 2
That's a very backwards thing to want to do, but you'd probably do it by exploding your string into an array of values, and using call_user_func_array to pass those values as the parameters to the function.
function blah($x, $y) {
echo "x: $x, y: $x";
}
$xy = "4, 5";
$params = explode(", ", $xy);
# Just like calling blah("4", "5");
call_user_func_array('blah', $params);
I'll warn you again however that you've probably chosen the wrong solution to whatever your problem is.
How you are wanting to do it, you can't. However, look in to call_user_func_array as it may solve what you are trying to do. Demonstration follows:
function blabla($param1, $param2){
echo "my cool code $param1 $param2";
}
$params = 'does,work';
call_user_func_array('blabla', explode(',', $params));
use explode() php function
function blabla($param){
$params = explode(',', $param);
$param1 = $params[0];
$param2 = $params[1];
}
$params = 'param1, param2';
blabla($params);
PHP is interpreting this as one argument because you have specified a single string, which just happens to include a comma; just something to bear in mind for the future.
Something very simple is:
function blabla($param1, $param2){
my_cool_code . $param1 . $param2;
}
blabla($param1, $param2);
First, a function name must not have a '$'. Secondly, you have only 2 params, you can pass both params through the function, like above.
The code is now good to use :)
Related
I am having situation where i want to pass variables in php function.
The number of arguments are indefinite. I have to pass in the function without using the array.
Just like normal approach. Comma Separated.
like test(argum1,argum2,argum3.....,..,,.,.,.....);
How i will call the function? Suppose i have an array array(1,2,3,4,5) containing 5 parameters. i want to call the function like func(1,2,3,4,5) . But the question is that, How i will run the loop of arguments , When calling the function. I tried func(implode(',',array)); But it is taking all return string as a one parameters
In the definition, I also want the same format.
I can pass variable number of arguments via array but i have to pass comma separated.
I have to pass comma separated. But at the time of passing i don't know the number of arguments , They are in array.
At the calling side, use call_user_func_array.
Inside the function, use func_get_args.
Since this way you're just turning an array into arguments into an array, I doubt the wisdom of this though. Either function is fine if you have an unknown number of parameters either when calling or receiving. If it's dynamic on both ends, why not just pass the array directly?!
you can use :
$function_args = func_get_args();
inside your test() function definition .
You can just define your function as
function test ()
then use the func_get_args function in php.
Then you can deal with the arguments as an array.
Example
function reverseConcat(){
return implode (" ", array_reverse(func_get_args()));
}
echo reverseConcat("World", "Hello"); // echos Hello World
If you truely want to deal with them as though they where named parameters you could do something like this.
function getDistance(){
$params = array("x1", "y1", "x2", "y2");
$args = func_get_args();
// trim excess params
if (count($args) > count($params) {
$args = array_slice(0, count($params));
} elseif (count($args) < count($params)){
// define missing parameters as empty string
$args = array_pad($args, count($params), "");
}
extract (array_combine($params, $args));
return sqrt(pow(abs($x1-$x2),2) + pow(abs($y1-$y2),2));
}
use this function:
function test() {
$args = func_get_args();
foreach ($args as $arg) {
echo "Arg: $arg\n";
}
}
I'm not sure what you mean by "same format." Do you mean same type, like they all have to be a string? Or do you mean they need to all have to meet some criteria, like if it's a list of phone numbers they need to be (ddd) ddd-dddd?
If it's the latter, you'll have just as much trouble with pre-defined arguments, so I'll assume you mean you want them all to be the same type.
So, going off of the already suggested solution of using func_get_args(), I would also apply array_filter() to ensure the type:
function set_names() {
function string_only($arg) {
return(is_string($arg));
}
$names_provided = func_get_args();
// Now you have an array of the args provided
$names_provided_clean = array_filter($names_provided, "string_only");
// This pulls out any non-string args
$names = array_values($names_provided_clean);
// Because array_filter doesn't reindex, this will reset numbering for array.
foreach($names as $name) {
echo $name;
echo PHP_EOL;
}
}
set_names("Joe", "Bill", 45, array(1,2,3), "Jane");
Notice that I don't do any deeper sanity-checks, so there could be issues if no values are passed in, etc.
You can use array also using explode http://www.php.net/manual/en/function.explode.php.
$separator = ",";
$prepareArray = explode ( $separator , '$argum1,$argum2,$argum3');
but be careful, $argum1,$argum2, etc should not contain , in value. You can overcome this by adding any separator. $separator = "VeryUniqueSeparator";
I don't have code so can't tell exact code. But manipulating this will work as your requirements.
In short, I have a function like the following:
function plus($x, $y){
echo $x+$y;
}
I want to tell the function its parameters as array like the following:
$parms = array(20,10);
plus($parms);
But unfortunately, not work.
I'm tired by using another way as the following:
$parms = array(20,10);
$func_params = implode(',', $parms);
plus($func_params);
And also not work, and gives me Error message:
Warning: Missing argument 2 for plus(), called in.....
And now, I'm at a puzzled.
What can I do to work ?
There is a couple things you can do.
Firstly, to maintain your function definition you can use call_user_func_array(). I think this is ugly.
call_user_func_array('plus', $parms);
You can make your function more robust by taking a variable number of params:
function plus(){
$args = func_get_args();
return $args[0] + $args[1];
}
You can simply accept an array and add everything up:
function plus($args){
return $args[0] + $args[1];
}
Or you could sum up all arguments:
function plus($args){
return array_sum($args);
}
This is PHP, there are 10 ways to do everything.
You need to adapt your function so that it only accepts one parameter and then in the function itself, you can process that parameter:
Very simple example:
function plus($arr){
echo $arr[0]+$arr[1];
}
$parms = array(20,10);
plus($parms);
You can easily adapt that to loop through all elements, check the input, etc.
Heh? The error message is very clear: you ask for two parameters in your function, but you only provide one.
If you want to pass an array, it would be a single variable.
function plus($array){
echo ($array[0]+$array[1]);
}
$test = array(1,5);
plus($test); //echoes 6
Use this:
function plus($arr){
$c = $arr[0]+$arr[1];
echo $c;
}
And the you can invoke:
$parms = array(20,10);
plus($parms);
I have really simple problem in my PHP script. There is a function defined which takes variable length argument list:
function foo() {
// func_get_args() and similar stuff here
}
When I call it like this, it works just fine:
foo("hello", "world");
However, I have my variables in the array and I need to pass them "separately" as single arguments to the function. For example:
$my_args = array("hello", "world");
foo(do_some_stuff($my_args));
Is there any do_some_stuff function which splits the arguments for me so I can pass them to the function?
Use
ReflectionFunction::invokeArgs(array $args)
or
call_user_func_array( callback $callback, array $param_arr)
Well you need call_user_func_array
call_user_func_array('foo', $my_args);
http://php.net/manual/en/function.call-user-func-array.php
You are searching for call_user_func_array().
http://it2.php.net/manual/en/function.call-user-func-array.php
Usage:
$my_args = array("hello", "world");
call_user_func_array('foo', $my_args);
// Equivalent to:
foo("hello", "world");
Sounds to me like you are looking for call_user_func_array.
http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
Isn't this what you want?
edit
ah... ok... how about this:
Passing an Array as Arguments, not an Array, in PHP
If you can change the code of foo() it should be easy to solve this in just one place.
function foo()
{
$args = func_get_args();
if(count($args) == 1 && is_array($args[0]))
{
$args = $args[0]
}
// use $args as normal
}
This solution is not recommended at all, but just showing a possibility :
Using eval
eval ( "foo('" . implode("', '", $args_array) . "' )" );
I know it's an old question but it still comes up as the first search result - so here is an easier way;
<?php
function add(... $numbers) {
$result=0;
foreach($numbers as $number){
$result+=intval($number);
}
return $result;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>
Source:
https://www.php.net/manual/en/functions.arguments.php#example-142
Ok, I'm looking into using create_function for what I need to do, and I don't see a way to define default parameter values with it. Is this possible? If so, what would be the best approach for inputting the params into the create_function function in php? Perhaps using addslashes?
Well, for example, I have a function like so:
function testing($param1 = 'blah', $param2 = array())
{
if($param1 == 'blah')
return $param1;
else
{
$notblah = '';
if (count($param2) >= 1)
{
foreach($param2 as $param)
$notblah .= $param;
return $notblah;
}
else
return 'empty';
}
}
Ok, so how would I use create_function to do the same thing, adding the parameters and their default values?
The thing is, the parameters are coming from a TEXT file, as well as the function itself.
So, wondering on the best approach for this using create_function and how exactly the string should be parsed.
Thanks :)
Considering a function created with create_function this way :
$func = create_function('$who', 'echo "Hello, $who!";');
You can call it like this :
$func('World');
And you'll get :
Hello, World!
Now, having a default value for a parameter, the code could look like this :
$func = create_function('$who="World"', 'echo "Hello, $who!";');
Note : I only added the default value for the parameter, in the first argument passed to create_function.
And, then, calling the new function :
$func();
I still get :
Hello, World!
i.e. the default value for the parameter has been used.
So, default values for parameters work with create_function just like they do for other functions : you just have to put the default value in the list of parameters.
After that, on how to create the string containing the parameters and their values... A couple of string concatenations, I suppose, without forgetting to escape what should be escaped.
Do you want to create an anonymous function? The create_function is used to create the anonymous functions. Otherwise you need to create function normally like:
function name($parms)
{
// your code here
}
If you want to use the create_function, here is the prototype:
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
I'm having the same problem, trying to pass an array to a created callback function... I think I'll create a temporary variable... It's ugly but I have better to do then torture myself with slashes, my code is already cryptic enough the way it is now.
So, to illustrate:
global $tmp_someArray;
$tmp_someArray = $someArray;
$myCallback = create_function(
'$arg1',
'
global $tmp_someArray;
// do stuff with $tmp_someArray and $arg1....
return($something);
'
);
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)