0

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

1
  • not how php works, sir. Aside that, functions don't begin with $. you may be better off expecting an array as your function argument and pass array('param1', 'param2') Commented Apr 12, 2013 at 3:18

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

You're the best, in fact, it's exactly what I wanted to do eheh, thx alot, what is call_user_func_array doing exactly ?
@YannChabot What it does is pass parameters to the function like you want. The array is an indexed array that holds them, and can pass as many parameters as the function allows.
0

use explode() php function

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

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

Comments

0

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.

1 Comment

I know ! I understood the problem, just didnt knew how to make PHP understanding that this string was not 'Hey, yo' but '"hey","yo"'
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.