Ethan Brouwer
Ethan Brouwer

Reputation: 1005

PHP Function named after the Value of a Variable

I have a PHP function that I need to create that executes PHP or HTML Code that is stored in a variable. That's one problem. Another problem is the fact that the function will be created multiple times and will need a unique name so I've named it after $title but I'm not sure if this will create the function from the value of $title or if it will create a function called $title or if it just won't work. This is my code:

$title = $_POST['sogo_aso_name'];
$output = $_POST['sogo_aso_output'];

Some Code Here...

function $title ($output)
{
    //Some Code Here to execute $output...
}

So... That's my problem. I'm not sure what will execute the $output cleanly so it can be shown on a page. And I don't know if the function will be named after the value of $title

Thanks for any help!

Ethan Brouwer

Upvotes: 0

Views: 95

Answers (2)

David Barker
David Barker

Reputation: 14620

What you're trying to do is unfortunately not possible. You could create namespaces if you need a common name to prefix your functions with.

namespace fArr {
    function func1 (args) {}
    function func2 (args) {}
}

To call them you can use:

namespace {
    fArr\func1($title, $output);
}

Generally you want to avoid creating totally anonymous functions. Maybe create a function that handles the title and output for all requests. Alternatively create a new object with the func name as a property and output assigned to it.

$title  = $_POST['sogo_aso_name'];
$output = $_POST['sogo_aso_output'];

// Store data in an object named after the value of $title
// Note that constant use of this can get very messy, and very confusing
$$title = (object) array('output' => $output);

Upvotes: 0

Leri
Leri

Reputation: 12535

You can use call_user_func like this:

call_user_func($title, $output);

But it's really strange to change name of one function.

Upvotes: 2

Related Questions