检查PHP函数是否返回null或nothing
我有这个密码检查PHP函数是否返回null或nothing,php,return-value,Php,Return Value,我有这个密码 $return = $ep->$method($params); if ($return === null) { throw new Exception('Endpoint has no return value'); } return $return; 有没有办法区分返回null的方法和不返回任何内容的方法?这是不可能的。如果未设置返回值,函数将自动返回null。是否可以使函数返回另一个值?布尔值可能为true,并检查该值或null。如果函数不返回任何内容,则
$return = $ep->$method($params);
if ($return === null) {
throw new Exception('Endpoint has no return value');
}
return $return;
有没有办法区分返回
null
的方法和不返回任何内容的方法?这是不可能的。如果未设置返回值,函数将自动返回null。是否可以使函数返回另一个值?布尔值可能为true,并检查该值或null。如果函数不返回任何内容,则不应测试其返回值。您应该知道哪些函数需要返回一些东西或什么也不返回,即使您不是编写它们的人。使用PHP7的返回类型声明功能:
function a(): void {
return null; // :(
}
function b(): void {
// :)
}
function c(): void {
return; // :)
}
你可以这样做:
ob_start();
echo trim($ep->$method($params));
$output = ob_get_contents();
ob_end_clean();
if (empty($output)) {
throw new Exception('Endpoint has no return value');
}
return $return;
对不起,正确答案是。是的,您可以修改并重新编译PHP源代码:PI并不总是编写正常调用的函数,是的,但在这种情况下,函数是动态查找的。那么根据其他答案和提供的信息,我预见的唯一解决方案是PHP解析自己的代码并查找“返回”函数声明中的关键字。如果($return===“”){},这是否不起作用?您必须使用反射来检查暗示的返回类型-比较
b()==null
仍然为真。