473,382 Members | 1,717 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 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 3210
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.