tags:

views:

29

answers:

2

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:

http://stackoverflow.com/questions/1290117/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?

+1  A: 

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
A: 

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