Calling a variable by passing variable name as a string - php

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.

I was able to resolve the problem by using ${$arg} notation as described by #waterloomatt above.

Related

PHP callback - array or arrow syntax?

Let's assume we have this function
<?php
function run($callback)
{
$callback($some, $params);
}
How to call it?
run($someObject->callback);
or rather
run([$someObject, 'callback']);
The first one seems better to me especially because of code suggestion but in documentation is used array notation.
Why is first one worse than second one?
The array notation is better because the arrow notation doesn't work. Functions in PHP aren't first class objects which can be passed around. Whenever you "pass a function", you must pass it by name; i.e. only its name. To pass an object method, you need to pass the object and the method name using the callable pseudo type notation.

How to get query string values in YII without PATH format?

I am having following url,
www.example.com/index.php?r=recommend/create&id=184?
title=Ruins%20of%20Mahabalipuram
&url=http://localhost/index.php/mediadetail/index/184
I need to get title and url which are query string parameters.
Has anyone worked on getting values in query string in Yii?
There is also the getParam() method in CHttpRequest.
Yii::app()->request->getParam('title')
I've found it a valuable shortcut, since it checks both $_POST and $_GET and gives priority to $_GET, so you can use it to override post variables in the address URL. It also performs null checks and you can provide a default value in the second parameter.
The drawbacks are that you can't use it for arrays and maybe it's a little bit verbose (compared to $_GET['title']).
Look the function parse_str, it would worked and if not, look parse_url but it's not necessary for what you want to do.
They'll automatically be available in your action as $_GET variables. Yii handles parsing them for you as part of the CHttpRequest object

PHP Function pulling an array that matches the parameter

$youtubes = array("lNT4H39G2rw","pF2_qvdm8DQ","_8ytwhhJwco","K16ZRFWR2Mc","9WuPxe7zc6Q","rXZIIclPnd0","J8ZwyN6E3_Q","OEWJbsh0z-4","o62-X0stdFM","aIIiww2Neq0","5TJc-VbNYg0","MYQa1Tgw_z8","alxzFm-bqug","UmI7oyllrlY","RGKFXDHFmn4");
function randomFromArray($data) {
global $$data;
echo $$data[rand(0,count($youtubes)-1)];
}
randomFromArray("youtubes");
I am trying to get this to work as a function, so I can enter the array name as a parameter. It is then supposed to echo a random entry from the array. The bit where it gets the random entry from array works on its own if I substitute it straight in, but I can't seem to get it working as a function.
Any help?
You're using the variable name $youtubes in your randomFromArray function in the call to count (but the variable is not available under that name there).
Btw., why don't you pass in (a reference to) the array instead of its name? Would be much tidier than using global $$data; The following code uses a reference to avoid copying the array (but remember that then, the outside array could be changed from inside the method):
$youtubes = // ...
function randomFromArray(&$data) {
echo $data[rand(0,count($data)-1)];
}
randomFromArray($youtubes);
dont call the function randomFromArray("youtubes"); in this way you call the function with youtubes parametar like a string. and inside the function itself you dont have a $youtubes variable. call the function like this randomFromArray($youtubes);
hope this would help
You are passing the string 'youtubes' into the function, not the array. You want to pass in the name of the array:
randomFromArray($youtubes);
$youtubes = array("lNT4H39G2rw","pF2_qvdm8DQ","_8ytwhhJwco","K16ZRFWR2Mc","9WuPxe7zc6Q","rXZIIclPnd0","J8ZwyN6E3_Q","OEWJbsh0z-4","o62-X0stdFM","aIIiww2Neq0","5TJc-VbNYg0","MYQa1Tgw_z8","alxzFm-bqug","UmI7oyllrlY","RGKFXDHFmn4");
function randomFromArray($data) {
echo $data[rand(0,count($data)-1)];
}
randomFromArray($youtubes);
There are some things fundamentally wrong here.
global $$data
Why is there a double $ sign? And where would this data be coming from?
echo $$data[rand(0,count($youtubes)-1)];
Your function doesn't know the variable $youtubes, since you have never defined it inside of the function. All your function knows is the $data variable that you are passing to it.
randomFromArray("youtubes"); You are passing a string to your function, rather then your array. You probably want this instead:
randomFromArray($youtubes); // Pointing to your actual array, rather then a string
Try reading up on PHP functions first before attempting to use them as you're lacking a lot of basic knowledge about them.
After you put a ; after global $$data, you can try this: $f = $$data; and then echo $f[rand(..)]; if you really want to use names instead variables as others suggested. And if you do that you can use the string (or $f) further in the function code.

How do I get the name of a variable variable?

So, I need the actual variable name "varName" from global space. This function is actually a method inside a class.
Code is arbitrary for simplicity
$varName = 'what ever';
public function save($var)
{
$i[varName goes here] = $var;
}
I don't know if this is even possible, but I think maybe with a callback?
If it's a global variable, you might be able to find out the original name with:
$varname = array_search($var, $GLOBALS);
But that's not overly reliable; a best guess. If two global variables would contain the same value, you would just receive the name of either of them.
Read about $GLOBALS variable in the documentation.
This is probably what you need. Depending on the way you determine which variable you need, you can for example user array_search() to find the proper name based on the value.
Caution: $GLOBALS is about global scope's variables.
EDIT:
But this would be still a guess. You may try the following method to determine the name of the passed variable with ~100% certainty:
Pass variable to the method with reference.
Use array_search() for finding the name of the variable. If only one key matches it, you have your name. If not, go to the next step.
Save the initial value of the variable and save the list of positions at which you have found matching elements.
Change the variable's value into new one. Perform another search based on new value and get positions that are also in the list of positions from point no. 3.
At this point you have probably found the name of the variable you are looking for.
But...
Is it really needed? I suggest that you should look for simpler solution, some better encapsulation of your code.
Ps. array_search() actually returns no more than one key (see documentation). You should know that and make searching for multiple results a little more sophisticated to not skip the correct one if more than one variable matches your search criteria. (EDIT2: As mario suggested, array_intersect($GLOBALS, array($var)) will suffice)
In C, you would use a macro. I don't think there's an equivalent in PHP.
You could pass the name of the variable to the function as a string, then in the function get the variable's value from GLOBALS or eval it.
Thanks for the solution!
Here is my test:
<?php
$varName = 'what ever';
function save($var)
{
$i[array_search($var, $GLOBALS)] = $var;
print_r($i);
}
save($varName);
?>
prints:
Array
(
[varName] => what ever
)

How to call a function with a variable number of parameters which correspond to an array values?

OK, I know it sounds weird but I need to make a function that will receive two parameters the first one is a string and the second an array (containing strings).
This function will then call sprintf. My first parameter will be $format and my array will correspond to the various $args.
How can I achieve this (if possible)?
Thanks!
Well you want the vsprintf() function.
Like Orbling answered, for this particular case you need vsprintf.
But, in a generic case, to call a function with variable number of parameters, you can use func_get_args() inside the function which you desire to accept multiple (any number of variable arguments). This function (when called inside your function) returns an array containing all the parameters passed while calling your function.

Categories