Empowering Coders to Shape Logic their Way
Functions can be a difficult topic to grasp if you’re a new programmer. I’m sure you were exposed to functions in math, but do you really understand what the term “function” means?
Think about an automotive plant:
- You bring the materials to the plant.
- You feed the plant with those materials.
- The plant takes the materials and somehow produces a car (we’ll be focusing on this one).
The plant itself is the function. If you were an engineer, you would know what machinery needs to go inside of the plant in order to produce the car. Since we said that the plant is the function in this case, the internals of the plant are the internals of the function. The engineer that’s implementing the internals of the plant literally translates to the programmer. The programmer knows how to construct the internals of the function.
Let’s create our own virtual automotive plant (function). We’ll start off easy. The engineer (programmer) will create the automotive plant (function) and the only thing that the plant will do is print out “I am an auto plant.” Inside of the actual plant, this could be done by a printer or even some person writing down the words. In our virtual plant (function) we can use the echo statement to print out the words.
Before we can do that, we have to understand the anatomy of the user-defined function.
function function_name() {
// function body
}
The function starts with the keyword function followed by the function name. The function name can be any valid PHP name. Function names follow the same naming convention as variables: letter or underscore, followed by a series of letters, numbers, or underscores. The parentheses come next. In this case, there are no arguments that are passed to the function (we’ll cover that later). After the parentheses, the opening curly brace signifies the opening of the function body. This is where you will place your echo statement (or any other code). Function bodies can have multiple lines of code; each line of code is separated with a semi-colon (go figure). Finally, the closing curly brace is used to signify the end of the function.
Let’s create our automotive plant function. The name of the function will be “automotive_plant” and the function will just echo out “I’m an auto plant.”
<?php
function automotive_plant() {
echo "I'm an auto plant<br>";
}
automotive_plant();
?>
Once the function is created, PHP will read it but it will not execute it. To get the function to execute the code that’s inside of its function body, we have to call that function. How do you call a function? You just write the function name and the parentheses. This is pretty standard across all programming languages. Don’t forget the semi-colon.
automotive_plant();
If we execute the code above, you will see “I’m an auto plant” on your screen.
Let’s look at an example with multiple statements inside of the function body. We’ll create a more generic function called plant(). That function will have a local variable (we’ll cover scope later) that’s only visible to the code inside of the function body called $type_of_plant. We’ll assign the string “automotive” to the $type_of_plant variable. We’ll then echo out what type of plant we just assigned to the $type_of_plant variable.
<?php
function plant() {
$type_of_plant = "automotive";
echo "I'm an " . $type_of_plant . " plant<br>";
}
plant();
plant();
?>
If you run the code above, you’ll get:
I’m an automotive plant
I’m an automotive plant
It’s executed twice because we called the plant() function twice. This is what’s so powerful about functions: code maintainability, scalability, and re-usability. Imagine that the plant() function had 5 lines of code. If you needed to call that function 5 times, we would write 5 more lines of code total:
plant();
plant();
plant();
plant();
plant();
f we didn’t have that function, we would have to write all 5 lines of code 5 different times. The code is exactly the same, but you just wrote 25 lines of code. What would happen if we needed to change something? We would have to modify each of the places where we placed those lines of code. What if we used the code in a thousand different places? We would have to modify the code in a thousand different places. With the function, we need to modify the code in only one place.
The $type_of_plant variable is unnecessary. I just wrote that to show multiple lines of code. What we really want is to be able to pass to the function what the type of plant we want it to display, such as egg-plant, automotive plant, vegetable plant, etc. Those are called arguments and will be covered in the next article.
In this article, we need to cover one more topic: functions calling other functions. Before we look at a concrete example, let’s revisit our real automotive plant. We left off with the employee printing out the statement “I’m an auto plant” using the help of a printer. The printer itself can be seen as a function. It knows how it can take input from a computer and place ink to paper in such a way that it translates the computer’s machine code into characters on paper. In this example, it knows how to take input from a computer and print out “I’m an automotive plant.” That printer function is located inside of the automotive plant function: function inside of a function. The automotive plant is what calls the printer function.
Let’s look at a simpler example. We’re going to create two functions:
- sayName()
- state_yourself()
The sayName() function will just echo out “My name is Dino.” The state_yourself() function will echo out “Hi, I am a robot from the future” and will then call the sayName() function. You will call (invoke) the sayName() function the exact same way: by writing the function name and parentheses. The only difference is that the sayName() function call will be placed inside of the state_yourself() function body.
As a side note, I used camel-case notation to write sayName() and snake_case notation (or underscore notation) to write state_yourself(). If you’re using the camel-case notation to name variable or function names, start with a lower-case character and separate each word with a capital letter; everything else should be lower-case. Underscore notation separates each word with underscores; each word is lowercase. There’s a huge debate out there on what the best type of notation you should use. Whichever you choose, stick to it.
<?php
function sayName() {
echo "My name is Dino";
}
function state_yourself() {
echo "Hi, I am a robot from the future. ";
sayName();
}
state_yourself();
?>
Let’s walk through the example above.
- PHP skips over each of the function declarations.
- PHP encounters the state_yourself() function call on line 12.
- It looks for and finds the function state_yourself() on line 7.
- PHP enters the state_yourself() function body and echoes out “Hi, I am a robot from the future.”
- PHP goes to the next statement and sees that it’s a function call to sayName().
- It finds the function sayName() on line 3.
- It enters the sayName() function body and echoes out “My name is Dino.”
- It reaches the closing curly brace of the sayName() function on line 5 and it closes the function.
- PHP returns back to the state_yourself() function and continues code execution after the sayName() function call.
- PHP encounters a closing curly brace on line 10; it ends the state_yourself() function execution.
- PHP returns to line 12 and sees that the next character is the semi-colon. It ends the statement on line 12.
- PHP continues execution and encounters the closing PHP tag (?>). It ends the execution of the code and sends the result to the user’s browser.
- The browser displays: Hi, I am a robot from the future. My name is Dino.”
It’s important to visualize the way that PHP moves through the code. I’m not going to get into the way that functions are placed onto the call stack in memory, but it’s something that’s definitely worth a read if you’re interested.
PHP Tutorial Series
Continue your learning with these articles
CONDUCTING LOOPS IN HARMONY WITH CONTINUE
Need to skip something in a loop? Use the continue statement to do so. Breaks exit loops and continues skip over a single iteration.
Empowering Coders to Shape Logic their Way
PHP – P35: User Defined Functions
Functions can be a difficult topic to grasp if you’re a new programmer. I’m sure you were exposed to functions in math, but do you really understand what the term “function” means?