Understanding PHP Functions
A function is a named block of code that defines a particular algorithm intended to solve a given problem. It may take extra information as input parameters to solve the intended problem. A function may return some values after it has completed its task (algorithm for finding a value) to where it was called (perhaps from another function). A function may also call itself to return to itself until a certain condition is met for the function to stop calling itself and return to the main caller function or context. A function that calls itself is called recursive function – because it recursively calls itself until a base case is met.
Functions at Runtime
Remember that a function is just a named block of code that can be executed residing in a computer’s memory during that period of execution. Next, this function is put on a function call stack that mimics a (last-in-first-out) data structure. The function that called this function must wait (or relinquish the execution flow to the called function) until this function completes and returns (the called function then relinquishes back the execution flow to the original caller). Now, when this function (the called function) completes its task, it must return to its original caller and all local variables and parameters are erased from the computer’s memory (except static variables) and no longer exit.
Types of Functions
The PHP scripting language embraces two types of functions that allow a developer to manipulate and structure PHP code.
Built-in Functions
A built-in function is simply a function you may just call (without defining it before) to accomplish a given task. This built-in function is already defined by other developers in a PHP module or library. For example the following list names some built-in functions you may use to work around your PHP coding:
Using a PHP Built-in Function
Here are some examples on how to use a PHP built-in function.
To use a PHP function, simply just call it by specifying its name and appending parentheses or brackets after the name and a semicolon “;” like so:
phpinfo ();
And this should be the output of executing the above code:
Another example:
And the output of executing the above code should give you the following result:
User Defined Functions
On other hand, user-defined function is simply a function declared by a developer (perhaps you) who uses the PHP language to write server-side program. Declaring a function means to specify the function keyword and possibly the name of the function after the keyword, followed by a pair of parentheses and a possible number of parameters (if any), and then followed by a pair of curly-brackets and a possible return value (if any).
What you should know about functions in PHP
- A function is declared to be used or called to avoid a repetitive code that does the same thing.
- A function may be called multiple times within the PHP code in a file.
- A function may return a value after it’s completed its task (the algorithms) to the function or context where it was called.
- The returned value of a function may be assigned to a variable for a later use within the code.
- A function may call itself and return to itself until a certain base case is met to return to the original caller.
- A function may take some extra information as parameters defined within its parentheses as the problem input to be processed to solve the problem.
Function Parameters
Function parameters designate problem input values that a function may require in order to properly accomplish its task for solving the problem. Function parameters may be declared as required or optional. If you call a function that specifies a required parameter and you don’t pass any argument corresponding to the required parameter then the parser will throw an error.
To declare an optional parameter simply provide an initial value for that parameter after any declared required parameter within the function’s parentheses.
Example:
Code output:
Passing Function Parameters
There are two ways to pass parameters within a functions header (parentheses)
- Passing by value (literal value)
Passing a parameter by value means that the function would interact with the value of the passed variable rather than the variable itself.
To pass by value in PHP, just pass the literal value to the function
2. Passing by reference (variable name)
On other hand, passing by reference means that the function would interact with the passed variable itself and consequently, the function would change the variable’s value.
To pass a parameter by reference in PHP, just preface the parameter with the (&) symbol in the function’s parentheses. Note that you must pass a variable when calling the function for the referenced parameter in the function’s header.
Example:
Code output:
Variable Scope
A variable scope is a place or context where the variable can only be recognized and used or accessed within the PHP code. There are two variable scopes in PHP namely global and local scope.
Global variables
A variable declared in the PHP code outside a function’s curly-brackets is considered a global variable because it’s declared in a global scope. Which means that any function can access and use the variable by applying the global keyword or accessing it with the super-global $GLOBALS array.
The following example should give you a clear understanding of a global scoped variable:
Code output:
Function Local Variables
A function local variable is a variable declared within the function’s parentheses or curly-brackets which must be deleted from the computer’s memory after the function has completed and returned to its caller. A local variable can only be recognized and accessed within the function that declares it.
Function Static Variables
A static variable in a PHP function is a variable that the computer’s memory retains even though the function declared it has completed and returned to its caller. Which means that if you try to access the variable’s value next time you run the same function you will get the last assigned value.
Code Output
Closure Functions
A function declared without a name is called a closure in PHP. A closure function may be used where you want to directly assign its return value to a variable or to pass a function definition in a function requesting a function as its argument (usually callbacks).
The following code snippet shows how to declare and use a closure function in PHP:
Add the code output should resemble the following:
A closure function can inherit parent’s scope variable
A closure function can inherit its parent scope variables (accept PHP superglobals, $this and variable with the same name as parameters) either by value or by reference. The syntax for inheriting the variables is by using the (use) language construct defined in PHP 7.4.0. Simply put the “use” keyword after the parentheses of the function and append a pair of parentheses with a possible number of variables (separated by comma) defined in the parent scope. The following code snippet should clarify the syntax to you:
Code output:
Arrow functions in PHP 7.4.0
Many programming languages embrace the idea of reducing the structure required to declare a function or method by the means of an “arrow function”. PHP also embraced the same idea in version 7.4.0. To declare an arrow function in PHP simply follow the following structure or syntax fn($parameter) => expression. The fn construct is used to declare the function and the $parameter is a possible number of parameters, and the => is the syntax of an arrow function followed by an expression to return. The expression can be enclosed in curly-brackets if needed.
Code output:
Recursive Functions
A recursive function is a function that may endlessly call itself if no base case is set for the function to return to its original caller. A base case is a condition set to determine when a recursive function should return to its original caller.
The following example should clarify to you how to declare and use a recursive function:
Code Output:
Getting Function Arguments
Getting a function’s arguments means accessing all unknown passed arguments to the function. The following code snippet should give you a clear demonstration:
Code Output:
Dynamic Function Call
Calling a function dynamically means that you can use PHP’s built-in functions to call a given function based on a certain condition.
Code output:
THE END
Conclusion
This article was a brief touch up on PHP functions and I hope the reader will try to find more resources about the topic to expand the horizon in the context.
Please feel free to contact me if you need any help or have some queries.
Email: [email protected]
Email: [email protected]
And you may checkout my website for code examples at https:www.codeparl.com
I will appreciate your comment!
Thank you for your patient reading.
THIS ARTICLE WAS WRITTEN BY HASSAN MUGABO