Adam
Adam

Reputation: 29079

PHP: Documentation of function list

I have a file which consist of user defined functions with CamelCase names :

// some useful comments
function functionOne(){
   return false;
}

// some other useful comment
function addTwoNumbers($x,$y)
{
   return 5;
}
...

I would like to output these functions sorted by name like

addTwoNumbers($x,$y) 
2 parameters 
Comment: some other useful comment

functionOne() 
0 parameters 
Comment: some useful comments

So far, I get a list of function names like this:

include '../includes/functions.php';

$allFunctions = get_defined_functions();

$userFunctions = $allFunctions['user'];
sort($userFunctions);

foreach ($userFunctions as $functionName) {
  echo $functionName. "<br>";
}

My main problem is that I do not know how to display the number of parameters of each function and the parameter variable names.

Further (but I could live with it) the function names are only displayed with lower case letters, so I can't read them in CamelCase.

And finally the comments are of course not shown. I was thinking of writing them in an array $comments['functionOne']="some useful comments".

So my main problem is how do you get the parameter variable names and number.

Upvotes: 1

Views: 155

Answers (2)

tektiv
tektiv

Reputation: 14187

To get paramater number and names, you can use Reflection in PHP :

function getFunctionArgumentNames($functionName) {
    $reflection = new ReflectionFunction($functionName);
    $argumentNames= array();
    foreach ($reflection ->getParameters() as $parameter) {
        $argumentNames[] = $parameter->name;   
    }
    return $argumentNames;
}

Then you'll have your parameter names, and the length of the returned array will give you how many there are.


More information can be found about it :

  • ReflectionClass
  • ReflectionObject
  • What is Reflection in PHP ?

    Another common use of Reflection is for creating documentation. It would be extremely labour intensive to write documentation about every method of every class of a large framework or application. Instead, Reflection can automatically generate the documentation for you. It does this by inspecting each method, constructor and class to determine what goes in and what comes out.

Upvotes: 3

buildok
buildok

Reputation: 785

Use ReflectionFunction class

for example:

$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
    print $param;
}

The ReflectionFunction class reports information about a function. See more http://php.net/manual/en/class.reflectionfunction.php

Upvotes: 0

Related Questions