I've got a list of variables. Let's call it a=1,b=2,c=3. I would like to pass the variable name to a function as a string and then retrieve its' value. Is there a way to achieve this in PHP? I', hoping to use this in page object pattern with Gherkin to pass a variable name to a gherkin step.
Asked
Active
Viewed 314 times
-1
-
I've done this in c# using reflection before. Hard to think of a way to do this in PHP as I'm relatively new to PHP. – Pubudu Jul 08 '19 at 17:21
-
2why actually should one need that? This sounds like a XY-problem to me – B001ᛦ Jul 08 '19 at 17:23
-
So you want to call `my_function('my_variable')` and then have _my_function_ read the value of `$my_variable` from memory? – waterloomatt Jul 08 '19 at 17:25
-
That's correct. – Pubudu Jul 08 '19 at 17:26
-
I would rather use the variable name to add more visibility in my test step as a string than passing the actual variable value to maintain abstraction and then call the actual variable value from page object by using it's variable name. For example, it makes the steps more readable if I pass variable name "passwordTextBox" rather than passing the actual value "textbox_ix_bbb_ks_bla_bla" – Pubudu Jul 08 '19 at 17:27
-
2You could manually build up the variable with `${'my_variable'}` (https://stackoverflow.com/a/16339701/296555) but you'll still have to deal with scope issues. This approach is rarely a good idea. – waterloomatt Jul 08 '19 at 17:34
-
2Why don't you use reflection in your `test step` to get the names of the arguments instead of adding unnecessary complexity to your application code? See an example here: https://stackoverflow.com/a/2692514/296555 – waterloomatt Jul 08 '19 at 17:37
-
You can pass a string of the form "a=1" and retrieve the name and its value in the function. – Jean-Claude Colette Jul 08 '19 at 17:44
1 Answers
0
I was able to resolve the problem by using ${$arg} notation as described by @waterloomatt above.

Pubudu
- 478
- 1
- 6
- 22