对调用方函数强制执行return语句



我只是想知道是否可以强制父方法从该父方法中调用的方法中返回值?假设我有:

public function myApiEndpoint()
{
// I DO NOT want to to have return statement here
$this->validOrUnprocessable();
// some other code
//return value
return $someValue;
}
public function validOrUnprocessable()
{
if ($condition) {
... here goes the code that forces return statement on myApiEndpoint function without putting the word `return` in front of this call...
}
}

换句话说,validOrUnprocessable方法,当它需要这样做时,会迫使或欺骗PHP认为myApiEndpoint返回值。当调用validOrUnprocessable或任何if条件时,我不想使用return语句。

我确实知道做我想做的事情的其他方法,但我想知道这样的事情是否可能。我对任何变通办法都不感兴趣,因为我非常清楚如何以许多其他方式实现我需要实现的目标。我只需要知道我所描述的是否有可能做到我所描述

我确实试着通过思考和其他与范围相关的事情来达到目的,但到目前为止运气不佳。有什么想法吗?

只是补充一下。我这么做是因为我想检查我能推多远。我正在为自己构建一个工具,我希望它尽可能方便易用。

如果不可能的话,我还有另一个想法,但这有点超出了这篇文章的范围。

您应该抛出一个异常。

public function validOrUnprocessable()
{
if ($condition) {
throw Exception('foo bar');
}
}

调用此方法的代码应该准备好捕获异常:

public function myApiEndpoint()
{
try {
// I DO NOT want to to have return statement here
$this->validOrUnprocessable();
// some other code
//this code will never be called because of exception thrown in validOrUnprocessable
return value;
} catch (Exception $e) {
//do something else 
return -1; //you can return another value as example.
}

return $someValue;
}

最新更新