Reputation: 5737
I am accepting a variable into a function.
For example, the variable is called $field
and I then want to name a variable by what is inside the $field
variable.
Say $field = 'randomName'
, I want my variable to be $randomName
.
Is this possible?
Thanks.
Upvotes: 1
Views: 101
Reputation: 53525
Yes it is possible:
$field = "randomName";
$$field = "test";
$$$field = "test 2";
echo $randomName . "\n"; //outputs: "test"
echo $test. "\n"; //outputs: "test 2"
Check this out
Upvotes: 1
Reputation: 18446
PHP has a language feature called variable variables. In your case:
$field = 'randomName';
$$field = "Hello world!";
echo $randomName; // prints out "Hello world!"
Upvotes: 1
Reputation: 11
It is possible (see "variable variables"), but this approach should be discouraged and it is often better to use a data structure (i.e. an array with keys) for this sort of dynamic operation.
Upvotes: 1
Reputation: 7784
$field = "randomName" ;
${$field} = "yeah" ;
${"randomName"} = "that works too" ;
Upvotes: 1
Reputation: 18833
You can assign variables as variable names.
$$field
This will do what it sounds like you're asking for.
Upvotes: 0
Reputation: 23777
You want variable variables?
See http://php.net/manual/en/language.variables.variable.php
Example
$varname = 'var';
$$varname = 'content';
print $var; // outputs 'content'
Upvotes: 0