How to create variable names dynamically

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

How to create variable names dynamically

Post by Benjamin »

If this is possible I would like to know how to do it..

Code: Select all

class sample
{
    function __construct()
    {
        $this->transferPost();
    }

    function transferPost()
    {
        foreach ($_POST as $key => $value)
        {
            $this->$key = $value; // <-- 
        }
    }
}
So if a variable named thisName is posted, I can then access that variable with

Code: Select all

$howdy = $sample->thisName;
Maybe that code I wrote up there will work but I'm assuming it's not that easy..
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

Have you tried it? You could execute that very nice script faster than it takes to write a post.

Don't make me start talkin' like a pirate!
(#10850)
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

:P Cool... Just in the middle of writing a big class and had a brainstorm.. Didn't realize it might work until after I finished writing it.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

You might want to change the channel... I think that station is off the air :D
Post Reply