3. Functions Flashcards
How do you define a function in PHP?
function funcName() { // Statements here. }
How can you write a PHP function that’s just short hand for some HTML?
Define the function, then exit PHP, write your HTML, then go back into PHP and finish the function.
What happens if you nest functions?
- Inner functions do NOT gain visibility to outer function arguments.
- Inner function also cannot be called until outer function has been called.
- Inner function cannot be used UNTIL outer function has been called at least once.
Generally, this is a bad idea to do.
When is a static variable initialized within a function?
Only once when it’s first called.
What are the two ways you can pass parameters to functions?
Value – Copy is passed in.
Reference – Pointer to the value is passed, modifications are reflected to the caller.
How do you pass a parameter to a function by reference?
Add an & before the parameter name.
How do you define a default parameter for a function?
Assign it in the function definition line. The only rule for this is all optionals need to be AFTER all required parameters.
How do you make a function with a variable number of parameters?
First, create a function with no parameters. Then within your function use the following functions to retrieve arguments.
What’s important to note about the variable parameters functions?
They can’t be directly passed to another function. See image.
What happens if you just DON’T pass some parameters to a function?
Those parameters will remain unset, and a warning is generated. It will still call the function though.
How can you use type hinting in a function definition?
State the type before the name of the parameter.
What’s the type of a function in PHP?
How can you use type hinting to get something you can invoke?
Set the type as callable.
How can you set the return data type of a function?
At the end of the function prototype, add a colon and the type
: int
When should you use return by reference for functions?
ONLY when you have a good technical reason for doing so. The PHP engine will already optimize, so don’t consider optimization.
What is a variable function?
A function that’s referenced by a variable, maybe passed to another function as a callback, that can then be called.