3

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
  • Your question is confusing and hard to understand. Could you clarify it a bit? Commented Jan 26, 2009 at 6:56

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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 $;

Comments

4

You can do something like this:

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

$foo = "mystring";
${$foo} = "a value";
echo $mystring; //will echo "a value";

Comments

1

https://www.php.net/language.variables.variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.