PHP: Print out all Variables passed to a Function

Working on old scripts can be quite annoying, particularly when you encounter an undocumented function and are trying to figure out firstly which inputs that function accepts, and secondly what it actually then does with it!

Of course, the easiest way of determining this is to call the function and print out what variables are coming into it, and thanks to some native PHP functions, this turns out to be quite the easy thing to do.

First up is func_num_args() which returns the number of arguments passed into the current user-defined function. Then comes the handy func_get_args() which returns an array which contains all the arguments (corresponding to the user-defined function’s argument list) passed into the function. Finally, func_get_arg() is used to return a specified argument from the passed in arguments, starting from a zero index.

If we grab a test argument to show all of the above functions in action, we get this: (grabbed off the main PHP documentation site)

function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs
\n"
; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "
\n"
; } $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "
\n"
; } }   foo(1, 2, 3);

Quite handy little functions, aren’t they?

(And to think that I didn’t even know of their existence up until now! :P)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged arguments, , parameters, , variables. Bookmark the permalink.
  • http://www.frontiercoffee.co.za Steve

    Thanks Craig. Very useful and more than just handy!

  • http://www.craiglotter.co.za Craig Lotter

    No problem, glad I could help out! :)

blog comments powered by Disqus