Simple Function Testing and Debugging in PHP

Published in Programming and Scripts on Friday, August 10th, 2007

When programming for the web, sometimes the need arises to test a function on the fly without being too intrusive. You may be debugging and need to test for a result, or simply testing. The following is a simple strategy that can help in those cases.

Firing a function from your browser

The concept is as simple as firing a function from your browser, and it leans on PHP's call_user_func_array.

I'm going to outline the concept as I have implemented it. This exact implementation may not work in your case, but perhaps you can adapt it to do so.

if(isset($_GET['f']) && function_exists($_GET['f'])) {
$func = $_GET['f']; // Get function name.
unset($_GET['f']); // Drop function from from get.
// Fire and print function, passing 
// remaining GETs as function parameters.	
print_r(call_user_func_array($func, $_GET)); 
exit;
}

In our CMS/Framework, we set up a controller with the code from above to respond at a given URL, for example http://www.example.com/__FOO. By passing a function name as a GET variable, in this case 'f', and the parameters necessary for that function to work as subsequent GET parameters, the result of that function will be printed to the screen.

So, http://www.example.com/__FOO?f=hello_foo&a=world would fire the function hello_foo('world'), perhaps printing Hello World! to the screen.

This allows for a quick and dirty test of a given function, and can be done remotely on a live site, if necessary, without touching any files or whatnot.

We hide this behind an authorization wall and also clean our parameters before they get to this level, so if you try this, keep these points in mind.

Comments and Feedback

This is an iteresting debuging. I have yet to look into debuging and error handeling in any organised way. Is your framework avalible to be looked at? I have not been impressed with the PHP frameworks that are distributed. Although I understand the task of catering for everyones wants is huge. The biggest gap that need to be filled is a framework for forms that allows advanced forms to be created in a short ammount of time, results lists with paging and result list fliters. Those are my main areas to explore in PHP as well as JavaScript style events.

Coincidently, I just wrote about this same function a few minutes ago: http://www.mutinydesign.co.uk/scripts/problems-encountered-with-php-dom-functions---3/

Check out the blog categories for older content