472,368 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,368 software developers and data experts.

create variables on the fly (dynamically)

bilibytes
128 100+
hi,

i was wondering how to create variables on the fly,
by this i mean: i have a pair of strings or an associative array with one string for Key and another for Value:

Expand|Select|Wrap|Line Numbers
  1. $var1 = 'hello';
  2. $var2 = 'johnny';
or --------------

Expand|Select|Wrap|Line Numbers
  1. array('hello'=>'johnny');

how could i manage to make of these two strings, a vairable with one becoming the name of the variable and the other the value.

Expand|Select|Wrap|Line Numbers
  1. echo $hello; //prints johnny

is there a thing like:

Expand|Select|Wrap|Line Numbers
  1. ${$var1} = $var2;
?


Thankyou.
Nov 6 '08 #1
5 3154
bilibytes
128 100+
The answer is to use eval()

if you want a variable to have the name of another variable's value, do :

Expand|Select|Wrap|Line Numbers
  1. $my_var_name = 'some_text'
  2. $my_value = 'some other text' 
  3.  
  4. eval( '$'.$my_var_name.' = \' '. $my_value.' \';' );
  5.  

(of course, you cannot do a variable with a wrong syntax: $myvalue ='some text'. 'some text' could never become the name of a variable, even if you write it yourself. $some text = parse error...)
Nov 6 '08 #2
Atli
5,058 Expert 4TB
Yes, you can do that.

In fact, if you combine your first example with your last example and then echo the variable $hello, you should get "johnny".

You can also do this using array key=>value pairs by using a foreach loop, like:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $array = array('hello' => 'John');
  3.  
  4. foreach($array as $_key => $_value) {
  5.     ${$_key} = $_value;
  6. }
  7.  
  8. echo $hello;
  9. ?>
  10.  
Which would print "John".

I have to ask tho, why are you doing this?
It seems like sort of a backwards logic, taking arrays and importing them into variables.

Why don't you just use the arrays as they are?
Why do you want to do $hello rather than $arr['hello']?
Nov 6 '08 #3
Atli
5,058 Expert 4TB
The answer is to use eval()

if you want a variable to have the name of another variable's value, do :
No. eval is never the answer! It's very very dangerous, if not just sloppy, to use eval. It causes all sorts of performance and security issues.

You can simply do:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $key = 'hello';
  3. $value = 'johnny';
  4.  
  5. ${$key} = $value;
  6. ?>
  7.  
Nov 6 '08 #4
bilibytes
128 100+
ok thanks for clarifying.

could i do:

Expand|Select|Wrap|Line Numbers
  1. $this->{key($array)} = $array[key($array)];
?

the point is that i want to make a class that would handle all the HTTP requests of my application.

and i am trying to put the $_REQUEST array's content into variables of an instance of that class, without having to put to many if conditions.

is it good to do this?

i think it clarifies the code but maybe its not a good practice.

please tell me if what i want to do is totally stupid. maybe its better to just use $_REQUEST['key']...


as i saw that, in PHP manual, in the extract() function documentation, they talk about using extract to handle $_REQUEST array, i thought it would be great to make an object for that. but there is no option to extract() the array content into object variables" $this->variable". extract() only extracts to normal vairables "$variable". that is why, i was trying to figure out how to do that...

long story!

thankyou
Nov 7 '08 #5
Atli
5,058 Expert 4TB
So basically, all you are trying to do is;
Expand|Select|Wrap|Line Numbers
  1. // to change this
  2. echo $_REQUEST['name'];
  3.  
  4. // into this?
  5. $request = new RequestObject();
  6. echo $request->name;
  7.  
Why?

Unless you plan on having your class automatically sanitize or validate your fields?

I usually get request variables via a controller class that automatically sanitizes the data, but it doesn't need to be as complicated as you are trying to make it.
A simple static "getField($key)" method that gets and processes the field before returning it to you usually does fine.
Nov 7 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Bil Muh | last post by:
Esteemede Developers, I would like to Thank All of You in advance for your sincere guidances. I am developing a software using Visual C++ .NET Standard Edition with Windows Form (.NET)...
4
by: vertigo | last post by:
Hello I need to create some objects durring program execution - but it's names are dynamically generated (depends on parameters). How can i do it ? Thanx Michal
3
by: Earl Teigrob | last post by:
I have a small application that consists of one aspx page with inline and dynamically loaded user and custom controls. When the page loads, I need to calculate a set of global SESSION variables...
7
by: pmclinn | last post by:
I was wondering if it is possible to dynamically create a structure. Something like this: public sub main sql = "Select Col1, Col2 from Table a" dim al as new arraylist al =...
25
by: Russell | last post by:
I want my code to be Python 3000 compliant, and hear that lambda is being eliminated. The problem is that I want to partially bind an existing function with a value "foo" that isn't known until...
12
by: Oliver Block | last post by:
Hi, does anybody know if it's possible to assign variables within css files? Best Regards, Oliver
1
by: dnn | last post by:
How can I access dynamically loaded variables? I am trying to load an external javascript file dynamically and then access its variables. The script is loaded by the onload handler. The code...
3
by: G | last post by:
Hello, I have a c# ASPX file, and a Code Behind file. This file has contents POSTED to it, around 15 form fields. Rather than manually catch each Request.Form - is there an easy way to...
1
by: stef mientki | last post by:
hello, I've a program where users can make modules, by just dumping them in a certain directory, then they will dynamically link into the program if needed. One of the communication channels...
8
by: =?Utf-8?B?U2hhd24=?= | last post by:
Hi; i just started research reflection and i'm wondering if i have an empty class file can i use reflection to add member variables and attributes dynamically and then instantiate the class? What...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.