Functions are self-contained blocks of code that can be called over and over again. Functions help your program become easier to understand and more modular while also reducing the amount of code you need to write to accomplish the same thing.

By dividing up more complicated logic into small pieces, functions help ensure your code doesn't grow out of control. Let's look at a simple function in PHP:

PHP
<?php function introduction() { echo('Hello, I am from New York City.'); } ?>

In general, to create a function, start with the function keyword, then the name of the function, in this case introduction.

Invoking

By itself, a function doesn't do anything. For the code inside of it to be executed, the function must be called, also known as invoking the function. Let's invoke our function from earlier:

PHP
<?php function introduction() { echo('Hello, I am from New York City.'); } introduction(); ?>
HTML
Hello, I am from New York City.

And just like that, the introduction function was invoked, causing whatever is inside to executing, giving us the text on our screen.

This is all nice, but what if you aren't actually from New York City and wanted your function to be a little more flexible?

Parameters

Functions support the passing in of information necessary for the function to execute its code. This information is called parameters or arguments.

Let's pass in a custom greeting and location to our introduction function.

PHP
<?php function introduction($greeting, $location) { echo($greeting . ', I am from ' . $location . '.'); } introduction('Hi', 'Los Angeles'); ?>
HTML
Hi, I am from Los Angeles.

Our new and improved introduction function takes two parameters now, $greeting and $location. It then uses these two to create a brand new string from it. It takes the greeting, appends text to keep the format of the introduction identical, then appends the custom location at the end.

Now this function can work for anybody, no matter where they live!

Return Values

In addition to making our code more flexible and reusable, functions can also return values to us. In our previous examples, the introduction function didn't return any data to us because its only job was to print text.

Let's create a function that takes in a parameter but also returns back data by calculating the circumference of a circle given a specified radius.

PHP
<?php function get_circumference($radius) { return 2 * $radius * M_PI; } $radius = 4; $circumference = get_circumference($radius); echo('A circle with a radius of ' . $radius . ' has a circumference of ' . $circumference); ?>
HTML
A circle with a radius of 4 has a circumference of 25.132741228718

Pretty cool, right? Our get_circumference function takes the radius that we pass in and returns the calculated circumference back to us. We assign that value to the variable $circumference so that we can use it in our code.

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.