开发者

Print_r to find allowable values for a method?

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 t开发者_如何学编程his, is there any way to determine the allowable values for the methods it returns?


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.


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)...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜