Introduction To PHP Functions

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

INTRODUCTION TO PHP FUNCTIONS

Defining Functions
Let’s get right to it and create our first function:
function greetLearner()
{
echo "Hello, Learner!\n";
echo "I hope you're enjoying PHP!\n";
echo "Love, Codecademy";
}
Let’s walk through the code above:

 We used the function keyword to start our function definition.


 We named the function greetLearner. Function names must start with a
letter or underscore, followed by any number of letters, numbers, or
underscores.
 We created a code block with curly brackets ({ }). The code inside this
code block will execute when our function is invoked.
 Within that block we wrote three instructions: echo "Hello, Learner!\
n!";, echo "I hope you're enjoying PHP!\n"; , and echo "Love, Codecademy";

With our greetLearner() function defined, we’ll be able to invoke the function


multiple times and print those strings without having to copy or retype the
three echo statements again and again.

A few notes on naming conventions: we typically snake case (separate


words with underscores) our variable names, but, in order to easily tell the
difference between variables and functions in our code, we’ll do something
different when naming functions. We’re going to use camel case for our
function names—we’ll start with a lowercase letter and then capitalize the
first letter of every new word: camelCase vs. snake_case. Another good practice
is to name functions in a way that describes what they do—typically we’ll
start function names with a verb.

In the next exercise, we’ll show you how to invoke a function. For now, let’s
get some practice defining them!

Instructions

1.
Define a function named praisePHP. You can leave the function body blank
for now.
Stuck? Get a hint
2.
Add at least one echo statement inside your function body which prints a
string praising the PHP language.
Stuck? Get a hint
3.
Now that your function is fully defined, run your program. Notice what
happens… or really what doesn’t happen.
INTRODUCTION TO PHP FUNCTIONS
Return Statements
As we build more complicated functions, we’ll often be using them to
process data. In order for the data to be useful, functions have the ability
to return a value in addition to performing instructions. Let’s look at an
example:
function countdown()
{
echo "4, 3, 2, 1, ";
return "blastoff!";
}
When the countdown() function is invoked it will print 4, 3, 2, 1,, but what
about the string "blastoff!"? This value will be returned. We have a lot of
options for what to do with a returned value. For example, we could
capture it in a variable:
$return_value = countdown(); // Prints: 4, 3, 2, 1,
echo $return_value; // Prints: blastoff!
This example is a little silly, since we could have just printed the string
within the function, but, as we continue to create more complicated
functions, the ability to return a value will become extremely useful.

Let’s get some practice returning a value from a function!

Instructions

1.
Write a function printStringReturnNumber() which prints a string and returns a
number value.
Stuck? Get a hint
2.
Capture your function’s return value in a variable named $my_num.
Stuck? Get a hint
3.
Use echo to print your $my_num variable.
More on Return Statements
The return keyword immediately stops a function. This means that any code
after a return won’t run.

Let’s compare two different


functions: announceRunning() and announceRunning2(). The first of these is
defined as follows:
function announceRunning()
{
echo "The first function is running!\n";
return "This is the return value of the first function.";
}

$first_result = announceRunning();
echo $first_result;
Let’s walk through the code above:

 We defined the function announceRunning().


 Next, we defined the variable $first_result and assigned as its value
the result of invoking the announceRunning() function. This actually did
two things. It executed the function causing "The first function is
running!/n" to be printed. It also assigned "This is the return value of
the first function." to $first_result.
 Finally, we printed $first_result.

That seemed to work as expected. In our terminal we saw:


The first function is running!
This is the return value of the first function.
Let’s contrast that to the following example:
function announceRunning2()
{
return "This is the return value of the second function.";
echo "P.S., I love you";
}

$second_result = announceRunning2();
echo $second_result;
In this example, the string "P.S., I love you" will never be printed! As soon
as the return statement is reached, the function will end. So in the terminal,
we’d see this output:
This is the return value of the second function.
Let’s use this new knowledge to fix some broken code!

Instructions

1.
Run the code to see its current output.
Stuck? Get a hint
2.
The notFound() function should print the string "ERROR: Page not found!\n" and
return 404. Fix the notFound() function so that it works as intended.
Stuck? Get a hint
3.
Great work! The greetLearner() function also isn’t quite right… We’d like all
three of those echo statements to execute and the function to return "<3".
Help!
Return Values
The value returned from a function is just that—a value. This means it can
be used in any manner we would normally use a value of that type. This can
take some getting used to. Take a look at the following code:
function returnFive()
{
return 5;
}

echo returnFive(); // Prints: 5


In the code above we defined a silly function, returnFive(); all it does is
return the number 5. Then we used echo to print the invoked function. The
way that the computer executes functions and handles their returns can
take getting used to, but it’s very similar to what we experienced with
numbers and variables:
echo 5 + 3; // Prints: 8

$num = 5;

echo $num + 3; // Prints: 8

echo returnFive() + 3; // Prints: 8


A computer evaluates 5 + 3 to 8. In the same manner, when a computer
encounters a function invocation, it will execute the code in the function’s
body and then evaluate to the function’s returned value. We need to think
of functions as both what they do (the instructions in their code block) and
what they return.
Let’s invoke more functions!

Instructions

1.
Use echo to print the return values of each of the three provided functions in
order. The challenge: you may not use more than one line of code or more
than a single statement (use only one semicolon).

Note: You can add space, new line, or other characters in between the
return values.
Returning NULL
What about functions without return statements? Any function without
a return returns a special value NULL. NULL is a special data type that stands for
the absence of a value.
function returnNothing()
{
echo "I'm running! I'm running!\n";
}

$result = returnNothing(); // Prints: I'm running! I'm running!

echo $result; // Nothing is printed


Let’s walk through the code above:

 We defined a function returnNothing()— the returnNothing() function


prints "I'm running! I'm running!\n" but has no return statement.
 We defined the variable $result and assigned it the value returned
when we invoke returnNothing().
 Since we invoked the function, I'm running! I'm running! is printed.
 Because the function does not have a return statement, the value
assigned to $result is NULL
 Finally, we print the $result variable, but, since its value is NULL, nothing
is printed.

Let’s play around with NULL!

Instructions

1.
Write a function createVacuum() which returns nothing.
2. NULL can be really quirky. You don’t need to worry about the details now.
But, just for fun, uncomment the line we provided at the bottom of the
code. Predict what it will output to the terminal. When you have a guess,
run the code to see.

Parameters
Functions that do exactly the same thing every time they run can save us
from having to repeat code in our programs, but functions can do more.

In the beginning of this lesson, we wrote a greetLearner() function that


printed the same friendly greeting every time it was invoked. That’s ok… we
guess… But what we’d really like is to print a customized greeting. We can
accomplish this by using parameters!

When we define a function, we can also define parameters. A parameter is a


variable which serves as a placeholder throughout the function’s code
block. When the function is invoked, it’s invoked with a specific value. As
the computer executes the function, it replaces each occurrence of the
parameter with the value that was passed in. The actual value passed in is
known as an argument.

Let’s look at an example:


function sayCustomHello($name)
{
echo "Hello, $name!";
};

sayCustomHello("Aisle Nevertell"); // Prints: Hello, Aisle Nevertell!

sayCustomHello("Codecademy learner"); // Prints: Hello, Codecademy Learner!


In the code above, we defined the sayCustomHello() function. It has
a $name parameter. We invoked the function twice:

 The first time, we passed in "Aisle Nevertell" as the argument. During


that invocation, the function assigned "Aisle
Nevertell" to $name so Hello, Aisle Nevertell! was printed.
 The second time we invoked the function with the
argument "Codecademy learner" so $name was assigned that value
and Hello, Codecademy Learner! was printed.

Let’s get some parameter practice!


Instructions

1.
Write a function increaseEnthusiasm() which takes in a string parameter and
returns that string appended with an exclamation mark.
Stuck? Get a hint
2.
Use echo to print the result of invoking your increaseEnthusiasm() function
with a string of your choice.
Stuck? Get a hint
3.
Write a function repeatThreeTimes() which takes in a string parameter and
returns that string repeated three times (without introducing characters
which didn’t appear in the original string).
Stuck? Get a hint
4.
Use echo to print the result of invoking your repeatThreeTimes() function with a
string of your choice.
Stuck? Get a hint
5.
Ready for a little trickiness? Use echo to print the result of invoking
your increaseEnthusiasm() with the result of invoking repeatThreeTimes() as the
argument passed into increaseEnthusiasm(). You can choose any string you
like for the argument to repeatThreeTimes().
Pass By Reference
We can invoke functions with variables or with values directly. When we invoke a function
with a variable as its argument, it’s as if we’re assigning the value held by that variable to the
function’s parameter. We assign a copy of the value held by the argument variable. The
variable argument and the parameter are distinct entities; changes made inside the function to
the parameter will not affect the variable that was passed in:

function addX ($param)


{
$param = $param . "X";
echo $param;
};
$word = "Hello";
addX($word); // Prints: HelloX
echo $word; // Prints: Hello
Let’s walk through the code above:

 We defined a function addX() which reassigns $param to its previous value appended


with "X".
 We defined the variable $word and assigned it the value "Hello".
 We invoked addX() with $word as its argument.
 During the function invocation, $param was reassigned and the function
printed "HelloX".
 When we printed $word after the function was invoked, it remained its original
value: "Hello".

If we do want to make permanent changes to a variable within a function, we can prepend the
parameter name with the reference sign (&). In this way, we assign the parameter to be an
alias for the argument variable. Both will refer to the same spot in memory, and changes to
the parameter within the function will permanently affect the argument variable.

function addXPermanently (&$param)


{
$param = $param . "X";
echo $param;
};
$word = "Hello";
addXPermanently($word); // Prints: HelloX
echo $word; // Prints: HelloX
In the addXPermanently() function we made $param a reference to the argument. When we
invoked the function with $word the changes made to $param permanently affected
the $word variable. Let’s practice!
Create a function convertToQuestion(). It should take a reference to a string
variable as its argument. The function should prepend the string with "Do
you think " and it should add a question mark (?) and new line character (\n)
to the end of the string. So the string "no" would become "Do you think no?\
n"

$example = "I'm nice";

convertToQuestion($example);

echo $example; // Should print: Do you think I'm nice?


Checkpoint 2 Passed

Stuck? Get a hint


2.
Great job! Let’s test your function to make sure it’s working properly. We’ve
provided you with three variables $string_one, $string_two, and $string_three.
Invoke your function three times—once with each of the three variables.
Checkpoint 3 Passed

Stuck? Get a hint


3.
At the bottom of your code, use echo to print each of the string variables to
confirm that their value has been permanently changed.
<?php

$string_one = "you have teeth";

$string_two = "toads are nice";


$string_three = "brown is my favorite color";

// Write your code below:

function convertToQuestion(&$str)

$str = "Do you think " . $str . "?\n";

convertToQuestion($string_one);

convertToQuestion($string_two);

convertToQuestion($string_three);

echo $string_one;

echo $string_two;

echo $string_three;

You might also like