![]() |
VOOZH | about |
The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.
When you find yourself copying and pasting blocks of code to reuse in different sections of your program, you’re ready to write a function. If you need to interact with the contents of a variable — change the case, find the length, trim, or sort — there is probably a built-in function for that. Functions are self-contained, reusable blocks of code that accomplish a specific task. They provide modularity and are one method of code reuse.
A function sits dormant until it is called. When a function is called, it performs the task defined in the function. A function typically takes input, performs an action, and returns the resulting output. The action that takes place inside of a function builds a relationship between the input and the output. The three main parts to think about when interacting with a function are the input, the relationship, and the output. Even when the input is not explicit, there is usually some implicit data relating to the code’s environment: date, time, system, file, line number, and so on.
In this tutorial, you will work with all the different pieces of a function, so that you can use functions in the best way to solve your challenge. We will start by writing user-defined functions. These functions will clarify the difference between arguments and parameters, pass variables by value and reference, set default values, and use type declaration to specify the acceptable types for input and output. By understanding scope, you’ll be able to manipulate the specific section of your code that needs to change while leaving other parts untouched. Once you understand the different aspects of a function and how they are affected by scope, you’ll be able to read and understand the documentation for the many built-in functions PHP provides right out of the box. You’ll use built-in functions to perform common programming tasks effortlessly.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
PHP is a popular server scripting language known for creating dynamic and interactive web pages.
Committed to helping software developers to be successful by solving challenges in both their careers and their parenting.
Editor at DigitalOcean, former book editor at Pragmatic, O'Reilly, and others. Occasional conference speaker. Highly nerdy.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.