try {
$attempts = 0;
retry:
throw new Exception('Oops!');
} catch (Exception $e) {
if ($attempts < 4) {
$attempts++;
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
goto retry;
}
echo $e->getMessage().PHP_EOL;
}The retry keyword can be used in a catch block to optionally execute an abritraty statement before jumping to the top of the try block.
# Litteral number example
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry 4 {
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
}
echo $e->getMessage().PHP_EOL;
}# Constant examples
const RETRY_TIMES = 4;
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry RETRY_TIMES { sleep(1); }
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\RETRY_TIMES { sleep(1); }
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\Bar::RETRY_TIMES { sleep(1); }
echo $e->getMessage().PHP_EOL;
}# Litteral number example
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry 4;
echo $e->getMessage().PHP_EOL;
}# Constant examples
const RETRY_TIMES = 4;
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry RETRY_TIMES;
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\RETRY_TIMES;
echo $e->getMessage().PHP_EOL;
}
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry \Foo\Bar::RETRY_TIMES;
echo $e->getMessage().PHP_EOL;
}Possibly useful in async contexts?
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry {
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
}
}try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry INF {
echo 'Fail - trying again...'.PHP_EOL;
sleep(1);
}
}try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry;
}Removed: It is impossible to disambiguate a expr and statement at the parser level, so the following syntax examples are not possible. The statements must always be wrapped with {}.
try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry 4 sleep(1);
echo $e->getMessage().PHP_EOL;
}try {
throw new Exception('Oops!');
} catch (Exception $e) {
retry sleep(1);
}
I'm sensing some discrepancy in using a keyword in such a different way as
catch. Couldn't we do something like this?The second argument would be optional, and I would also accept these cases:
In this way it seems more coherent and elegant. What do you think?