0

I stumbled across this page which talks about the very handy new reflection class that ships with PHP5 and returns all the methods and properties of a class:

print_r to get object methods in PHP?

Following on from this, is there any way to determine the allowable values for the methods it returns?

Community
  • 1
  • 1
  • I'm not sure I understand what you're asking, are you looking for the method's parameter list or are you looking for the method's return values? I'm not sure of any way to do either programmatically, the best resource is the doc at http://php.net – bimbom22 Jul 15 '10 at 19:56
  • Do your classes have doccomments, which state the possible return values? If so, I think these may be extracted using Reflection. – NikiC Jul 15 '10 at 20:05

2 Answers2

1

You mean determine the allowed types of return values, and range of return values, for some method in some class? Very very hardly, I think. After all, there is no way of defining or hinting a return value in PHP. So I could do the following:

class .... {

function myFunction()
 {
    ... some code ....
   if (condition) return "A";
   .... more code .....
   if (condition2) return 2;
   .... more code ....
   if (condition3) return $_POST["number"];
 }
}

this is a totally screwed-up example of course, but you get my point. The possible types of the return value are extremely hard to predict because I could return anything at any point.

I think the best one can do is solve this in documentation blocks. If you follow phpDoc notation:

/** 
 * @desc Searches for a record.
 * @return int the number of found records.
 */
 function myMethod()
  { ....

many IDEs are able to at least give you a hint about the expected return type when you type a call to the method.

Unicron
  • 7,275
  • 1
  • 26
  • 19
0

Well, it depends on what you mean by "allowable values". If it's available in the doc-block, you can probably find it with Reflection... To find the return value:

class foo {
    /**
     * @returns boolean When false
     */
    public function bar($x, $y = 'bar') {
    }
}

$reflector = new ReflectionMethod('foo', 'bar');
$comment = $reflector->getDocComment();
if (preg_match('#@returns (\\S+)#', $comment, $match)) {
    echo "Method returns: ".$match[1];
}

produces:

Method Returns: boolean

Then, you'd just need to parse out what you want from that doc comment... Note it can be a type OR a class (or a grouping of multiple, boolean|null|string|DOMNode)...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314