Reputation: 37
I am a little new to the PHP world and despite my googling and manual reading, I can't
I am currently (ethically!) scraping a website that has a number of different categories (let us call them 'alpha', 'beta', 'gamma').
Currently, I go through these steps:
Then go through the elements to grab the information.
$alpha_one = $element -> find etc;
$alpha_two = $element -> find etc;
$alpha_n = $element -> find etc;
$beta_one = $element -> find etc;
$beta _two = $element -> find etc;
$beta_n = $element -> find etc;
All of the tables are the same for alpha, beta, gamma; thus I would like to write a function, but I am struggling with how to include the argument name in the variables I create. This was my idea, but it does not work.
function grab($argument) {
$argument . "_one" = $element -> find etc;
$argument . "_two" = $element -> find etc;
$argument . "_n" = $element -> find etc;
}
Thus, I could use:
grab('alpha');
grab('beta');
grab('gamma');
without having to write out the code for each table
I've looked into 'magic methods', but cannot swing it into working. I would really appreciate if some PHP wizard could shed some light upon this. Thank youu!
Upvotes: 0
Views: 77
Reputation: 4025
Just do this:
function grab($argument) {
${$argument . "_one"} = $element -> find etc;
${$argument . "_two"} = $element -> find etc;
${$argument . "_n"} = $element -> find etc;
}
Upvotes: 0
Reputation: 1529
$argument only exists inside the function scope. It will not have any effect outside this function. If you're using a class you can create all possible variables (not recommended) and call:
$this->{$argument . "_one"} = ...
or store them in an array variable (best way):
$this->myArray[$argument . '_one'] = ...
Upvotes: 0
Reputation: 360872
That code is rather pointless. the $argument . "_one"
variable would exist ONLY within the function, and be destroyed when the function returns. You probably want something more like this:
function grab($argument) {
$data = array();
$data[$argument . "_one"] = ...
$data[$argument . "_two"] = ...
etc...
return ($data);
}
Essentially: build an array with dynamic key names, based on your $argument
, then return the entire array to the calling context.
Upvotes: 1