Jump to content

Dynamic Function Names/calls


coplan

Recommended Posts

I'm writing a modular system, and I want to be able to dynamically call specific functions based on the $_GET[] variables.  All the modules will have a standard naming protocol for functions.  For example:  ?_module_main() where '?' is the name of the module. 

 

Now, say the url of the page is http://whatever.com/?go=news, I want to be able to call the main news function, or news_module_main().  I need to dynamically call that function by replacing the first part of the function name. 

 

What is the best way to handle that?  I've already tried: 

 

$content = $_GET['go']._module_main();
// and
$content = $_GET['go'].'_module_main()';

 

Both result in undesired effects. 

 

Your thoughts?

Link to comment
https://forums.phpfreaks.com/topic/41501-dynamic-function-namescalls/
Share on other sites

i'd use a switch statement:

<?php
        switch($_GET['go']){
                case "news":
                        //call your function here
                        break;

                case "something else":
                        //call something else here
                        break;

                default:
                        break;
        }
?>

try this snippet

 

<?php
function f_A () {
    echo "<p>A called</p>";
}

function f_B () {
    echo "<p>B called</p>";
}

if (isset($_GET['func'])) {
    $fname = 'f_' . $_GET['func'] ;
    $fname();
}

?>

<form>
Select function A or B <br><br> 
<input type='radio' name='func' value='A'> A<br>
<input type='radio' name='func' value='B'> B<br>
<input type='submit' name='action' value='Call function'>
</form>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.