Yann Chabot
Yann Chabot

Reputation: 4869

Use a variable to define PHP function parameters

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

Upvotes: 0

Views: 165

Answers (5)

Ouzayr Khedun
Ouzayr Khedun

Reputation: 5

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 :)

Upvotes: 0

Diana E
Diana E

Reputation: 430

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.

Upvotes: 0

user229044
user229044

Reputation: 239291

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.

Upvotes: 3

Jon
Jon

Reputation: 4736

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));

Upvotes: 1

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

use explode() php function

function blabla($param){
  $params = explode(',', $param);
  $param1 = $params[0];
  $param2 = $params[1]; 
 }

 $params = 'param1, param2';
 blabla($params);

Upvotes: 0

Related Questions