0

I would like to pass a parameter to a function. However, inside this parameter, I use variables that are defined inside the function. For example:

<?php

function foo($var){
    $test = "test";
    echo $var;
}

foo($test);

?>

In this example, I would like for the function to print out "test". Of course, this returns an error. However, this is what I am trying to do.

3
  • That does not seems to make a lot of sense to me... why would you want to do this? (it's not possible btw, unless you make $test global, which defeats the purpose of defining it inside the function). Variables defined inside function should stay local, not accessible to the outside, to keep the code decoupled. Commented Oct 18, 2012 at 5:06
  • The function contains a foreach, with foreach($array as $post), and I'm using the variable $post in the parameter. Commented Oct 18, 2012 at 5:07
  • Why are you passing $post as argument? Or do you mean the parameter name is $post? $post will be populated with each element in $array during the loop. I still don't understand and I'm even more confused. Commented Oct 18, 2012 at 5:09

1 Answer 1

2

You can accomplish this with using variable-variables, though I don't understand why you'd want/need to:

function foo($var){
    $test = "test";
    echo $$var;
}

foo('test');

Notice in the echo statement inside foo(), the variable has two $ leading. This is a variable-variable and $var's value will be treated as a variable-name. So, by calling foo('test'); (the parameter being a string in this case), $$var will evaluate to $test.

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

2 Comments

@Sang: Note that using variable variables is generally a poor design choice. If you would explain which problem you are actually trying to solve, we could help you better.
@FelixKling I believe also it could be better, however variable-variables working also ... I agree with you, if he provides an original part of code, it would be much better for him at least.

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.