php - I'm about to use a goto statement
Get the solution ↓↓↓Save me from raptor death - is there any better way to handle this kind of structure?
while(condition) {
$this->phase1();
$this->phase2();
$this->phase3();
$this->phase4();
}
Throughout either one of those methods, the condition could be met. IMMEDIATELY after the condition is met, the loop MUST exit. If I could callbreak;
inside ofphase2();
for example, I wouldn't need a goto statement (but of course, that would throw an error).
Answer
Solution:
Return a boolean to execute each stage until successful.
while (condition) {
if ($this->phase1() || $this->phase2() || $this->phase3() || $this->phase4()) {
// Success!
}
}
Answer
Solution:
Or you could use the State pattern!
In summary, instead of having a goto statement, change the internal state of$this
such that methodsphase1
,phase2
,phase3
andphase4
have no effect and are empty functions. Since they will be empty functions, you'll fly right through 'em and exit the loop!
You'll probably also need a pinch of events or the Observer pattern, to know when to change state.
Answer
Solution:
Return a boolean from the different phases. I would returnfalse
if it didn't succeed, then check for that andbreak
.
Answer
Solution:
Throw an exception... sounds exceptional...
try {
while(condition) {
$this->phase1();
$this->phase2();
$this->phase3();
$this->phase4();
}
} catch (Exception $e) { }
Answer
Solution:
One way might be to useif()
statements to check for a return value from eachphase*()
and break the while loop.
Something like this:
while (condition) {
if ($this->phase1()) { break; }
}
Answer
Solution:
How about wrapping each of the phases in anif
:
while(condition)
{
if(condition)
{
$this->phase1();
}
if(condition)
{
$this->phase2();
}
if(condition)
{
$this->phase3();
}
if(condition)
{
$this->phase4();
}
}
Of course, this could probably be made more compact with a bit of planning and a loop.
Answer
Solution:
Please don't use a goto statement, think to the coder who will herit your code base
if your condition it's not too much of overhead, you could
while(*condition*){
$this->phase1();
if (*condition*){
$this->phase2();
}
...
}
Answer
Solution:
$phases=array('phase1','phase2','phase3','phase4');
foreach($phases as $phase){
$this->$phase();
if(condition)break;
}
Also , you can use exceptions if you want to break out from inside of the function.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function update() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.