tags:

views:

277

answers:

4

How do i dynamically assign a name to a php object?

for example how would i assign a object to a var that is the id of the db row that i am using to create objects.

for example

$<idnum>= new object();

where idnum is the id from my database.

+1  A: 

this little snippet works for me

$num=500;
${"id$num"} = 1234;
echo $id500;

basically just use the curly brackets to surround your variable name and prepend a $;

John Boker
+3  A: 

You can do something like this:

${"test123"} = "hello";
echo $test123; //will echo "hello"

$foo = "mystring";
${$foo} = "a value";
echo $mystring; //will echo "a value";
sam
+8  A: 

You can use the a double dollar sign to create a variable with the name of the value of another one for example:

$idnum = "myVar";

$$idnum = new object(); // This is equivalent to $myVar = new object();

But make sure if you really need to do that, your code can get really messy if you don't have enough care or you abuse of using this "feature"...

I think you can better use arrays or hash tables rather than polluting the global namespace with dynamically created variables.

CMS