Variable function calls
When using AJAX or sending vaiables to a PHP page to run a function there is a nice peice of code I like to put at the top of the PHP page. It is a peice of code that I use to run a function by passing its name through a variable. This allows you to GET or POST to a page many times and preform multiple functions. Here is the code and I’ll explain a bit more of a few ways that you can use it;
1 2 3 4 5 6 7 8 9 10 11 | <?PHP //if passed the variable 'function' through GET or POST if($function = $_REQUEST['function']){ //if function exists, run function if(function_exitst($function)) $function(); //else show error else echo 'Error: function '',$function,'()' does not exist.'; //Exit script exit; } ?> |
So to reiterate this is what this function does.
If the page is passed the varaible ‘function’ (either through GET or POST, hence the $_REQUEST) then it knows to run a function on the page.
It’ll then set the passed variable to the $function variable, and test to see if the function exists (by using PHP’s function_exists() function)
If the function does exists, the code then calls if ($function();), else it’ll show an error.
for example you could use this code like so;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?PHP //if passed the variable 'function' through GET or POST if($function = $_REQUEST['function']){ if(function_exitst($function)) $function(); else echo 'Error: function '',$function,'()' does not exist.'; exit; } function submitForm(){ $value = $_POST['field1']; echo 'You inputed ',$value,'.'; } ?> <html> <head> <title>Sample</title> </head> <body> <form action="<?= $_SERVER['PHP_SELF']; ?>?function='submitForm'" method="POST"> <input name="field1" type="text" /> <input type="submit" value="submit" /> </form> </body> </html> |
So the form will submit to itself, and run the function ’submitForm’ when it does so. Of course this is a very simple example.
you can download the complete version of this code, on my code page
