for example, in PHP code like this:
if($this->function1() && $this->function2())
{
//everything is alright
}
else
{
//function1 or function2 returned false
//whodunnit?
}
Is there a language construct or something that can help me find out the culprit in the else block? I don't want to have to run the conditions once again, just to find out what went wrong.
Please bear with my pseudo-code. My actual code will look totally out开发者_JAVA百科-of-context here... and I'm using CodeIgniter, by the way.
if($this->function1()) {
if($this->function2()) {
// both worked
} else {
// function1 returned a true value
// function2 returned a false value
}
} else {
// function1 returned a false value
// (you could optionally call $this->function2() here)
}
or, if you always want to run both functions:
$result1 = $this->function1();
$result2 = $this->function2();
if($result1 && $result2) {
// everything is okay
} else {
// look at the results to figure out what to do
}
or, if you want to do the first but without 2 levels of indentation:
if(!$this->function1()) {
// function1 returned false
// (you can call $this->function2() here if you want)
} elseif (!$this->function2()) {
// function2 returned false
} else {
// everything is okay
}
I want to use the name of the function that caused the error.
This is somewhat ugly. I wouldn't use it (= "for this purpose").
Also I'm making this CW to eschew the downvotes.
if ($this->function1($failed="func1") && $this->function2(.., $failed="func2")) {
...
}
else {
print $failed;
This syntactic workaround necessitates that you can fill up the methods parameters with the required number and pass the fake $failed
parameter in an unused spot. It in fact just adds this variable to the local variable scope.
You could redesign this if-statement more clumsily with more && ands and () parens to the same effect. This is just somewhat compacter. Yet I'm not sure if I understand why you would want a string with the failed function name, not just a boolean, or what's up with the if
phobia.
Most trivial solution: store the results of both functions in variables and check them in your if-condition.
try{
functionA();
functionB();
}catch(YourExceptionType $e){
//use $e to know what, where, and why it happened
}
That's what I would do
and if you are not throwing exceptions you may use "or", because when function is true then the second part of the or will never be run:
functionA() or somethingWentWrong();
functionB() or somethingWentWrong();
but I still recoment try/catch
You can use temporary variables in the if
itself:
if ($f1=$this->function1() and $f2=$this->function2()) {
Then later check them.
Note that I replaced &&
with and
to avoid extra parenthesis (the and
has lower precedence than the assignment).
精彩评论