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

Home Posts Topics Members FAQ

create variables on the fly (dynamically)

128 New Member

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;

Nov 6 '08 #1
5 3246
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' 
  4. eval( '$'.$my_var_name.' = \' '. $my_value.' \';' );

(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
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');
  4. foreach($array as $_key => $_value) {
  5.     ${$_key} = $_value;
  6. }
  8. echo $hello;
  9. ?>
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
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';
  5. ${$key} = $value;
  6. ?>
Nov 6 '08 #4
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!

Nov 7 '08 #5
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'];
  4. // into this?
  5. $request = new RequestObject();
  6. echo $request->name;

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

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
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
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.
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
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.
by: Oliver Block | last post by:
Hi, does anybody know if it's possible to assign variables within css files? Best Regards, Oliver
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";
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
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
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...
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...
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,...
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...
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,...
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...
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...
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...
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...
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.