473,895 Members | 2,364 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

create variables on the fly (dynamically)

bilibytes
128 New Member
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 3246
bilibytes
128 New Member
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 Recognized Expert Expert
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 Recognized Expert Expert
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 New Member
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 Recognized Expert Expert
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
3574
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) template. Briefly -------------------------------------------------------------------------------------------- I need to create dynamically some controls on the forms, and display these
4
2307
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
1503
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 that will be used by the loaded controls. The problem I am having in finding a place where the session variables will be calculated before any of the page controls or dynamically loaded controls try to access them.
7
6805
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 = LoadOracleData(sql) '____Do amazing things
25
2591
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 run-time: someobject.newfunc = lambda x: f(foo, x) The reason a nested function doesn't work for this is that it is, well, dynamic. I don't know how many times or with what foo's this will be done.
12
1502
by: Oliver Block | last post by:
Hi, does anybody know if it's possible to assign variables within css files? Best Regards, Oliver
1
1923
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 looks like this: var constants = document.createElement("script"); constants.src = REL_PATH + "extensions_demo/js/constants_" + MY_LANGUAGE + ".js"; constants.type ="text/javascript";
3
1990
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 simply create a loop which does the following: 1: Look for ALL posted form fields
1
1174
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 I use, is a general global file, which should be imported by all user modules. One of the things a user should be able to do is to create " global
8
3871
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 i would like to be able to do is start with and empty class, then depending on the data provided to me by a config file, add the member variables and attributes to the class temporarily. when the app is shutdown all changes would be gone. can...
0
9990
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9835
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10845
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10935
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10473
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9649
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8028
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5863
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4689
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.