Exceptions and Generators Flashcards
Describe PHP’s exception model.
Code can be surrounded in “try” blocks, for catching exceptions. Each try must have at least one corresponding catch or finally block. The thrown object must be an instance of the Exception class or a subclass of Exception, or a fatal error will result.
What happens when an extension is not caught?
A PHP fatal error will be issued, unless a handler has been defined with set_exception_handler().
What’s a finally block?
It may be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
Can exceptions be cloned?
No. Attempting to clone an Exception will result in a fatal E_ERROR error.
What’s one thing you should do if you extend the built-in Exceptions class and re-define the constructor?
It’s recommended that you also call parent::__construct() to ensure all available data has been properly assigned.
What are generators?
Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.
A generator is the same as a normal function, except…
…instead of returning once, a generator can yield as many times as it needs in order to provide the values to be iterated over.
Can a generator return a value?
No. Doing so will result in a compile error.
Is an empty return statement valid syntax within a generator?
Yes. It will terminate the generator.
What does a generator function return when called?
An object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.
A yield statement looks like a return statement, except that…
…instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
What must you do if you use yield in an expression context (for example, on the right hand side of an assignment)?
You must surround the yield statement with parentheses.
$data = (yield $value); //valid $data = yield $value; //not valid
Can you yield a key/value pair?
Yes.
How can you yield a NULL value?
Call yield without an argument to yield a NULL value with an automatic key.
Can generator functions yield values by reference as well as by value?
Yes. This is done in the same way as returning references from functions: by prepending an ampersand to the function name.