function a(){
b(1); // Returns true
b(0); // Echoes "Just some output"
}
function b($i_feel_like_it){
if($i_feel_like_it){
return return true;
}else{
echo "Just some output";
}
}
是否有可能从不同的函数中调用"返回"函数?
这样做的目的是我有一个类有很多函数…而不是写一堆代码来决定他们是否应该返回一些值,我想简单地放一个函数,如"validate()",并有函数调用返回如果必要,否则继续函数。
我想知道这是否可能。
总之,NO。感谢上帝,允许这样做会使它成为一种非常奇怪的语言,你可能不会依赖任何函数的返回。
可以抛出异常,但请参阅手册。这样,您就可以让被调用的方法影响被调用方中的流控制——尽量不要过度使用它们来实现这一点,因为过多使用这些方法会使代码变得非常难看。
下面是一个如何使用异常进行验证的例子:
class ValidationException extends Exception { }
function checkNotEmpty($input) {
if (empty($input)){
throw new ValidationException('Input is empty');
}
return $input;
}
function checkNumeric($input) {
if (!is_numeric($input)) {
throw new ValidationException('Input is not numeric');
}
return $input;
}
function doStuff() {
try {
checkNotEmpty($someInput);
checkNumeric($otherInput);
// do stuff with $someInput and $otherInput
} catch (ValidationException $e) {
// deal with validation error here
echo "Validation error: " . $e->getMessage() . "n";
}
}
不,不是。您必须检查b()返回什么,如果a()为真,则返回a()。
function a() {
if (b(1) === true)
return true; // Makes a() return true
if (b(0) === true)
return true; // Makes a() echo "Just some output"
}
function b($i_feel_like_it) {
if ($i_feel_like_it){
return true;
} else {
echo "Just some output";
}
}
你所尝试的是不可能的。查看return
模板间距
function a()
{
b();
return $a;
}
function b()
{
c();
return $b;
}
如果您希望a()
从b(1)
的true返回true,那么您可以使用return a();