Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Bookmark and Share
Lecture Comments (4)

3 answers

Last reply by: Russell Burnham
Thu May 16, 2013 7:14 PM

Post by Russell Burnham on April 18, 2013

Matthew, I can't get the return to work, here is my code:

function testrr($num){
if ($num == 1){
return 'one';
elseif ($num == 2){
return 'two';



This always returns blank.

Am I doing something wrong?
Please help.

User-Defined Functions

  • Defining a function requires four parts:
    • the function keyword
    • a function identifier
    • a function parameter list
    • a function statement group, or ‘function body’
  • Function parameters are variables defined in a function’s definition that can be used within the function’s body. They are initialized by arguments passed to the function each time it is called.
  • Return values of functions are specified using a return statement.
  • Return values can be of any PHP data type. If a return statement is never executed within a function, NULL is returned.
  • The include_once construct functions exactly as an include statement, except that if the file specified has already been included it will not be included again. require_once functions like a combination of include_once and require .
  • Additional Resources:

User-Defined Functions

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:16
    • Lesson Overview
  • Defining Functions 1:29
    • Four Parts of Defining a Function
    • Functions Example 1
  • Function Parameters 5:29
    • Function Parameters
    • Functions Example 2
  • Return Statements 12:53
    • Return Statements
    • Functions Example 3
  • Where to Define Functions 20:34
    • Where to Define Functions
  • include_once Construct 22:10
    • include_once Construct
    • include_once Coding Example
  • Reasons to Use Functions 27:44
    • Take Advantage of Code Reuse
    • Improve Code Readability
    • Use Instead of 'content' Include Files
  • Web Application Development 34:42
    • Version 10.0 Changelog
  • Version 10.0 Coding Example 37:55
    • Version 10.0 Coding Example
  • Outputting HTML in Functions 47:04
    • Outputting HTML in Functions
    • Example
  • Coding Conventions 53:16
    • Coding Conventions
  • Homework Challenge 54:33
    • Homework Challenge

Transcription: User-Defined Functions

Hello again, and welcome back to's Introduction to PHP course.0000

Today's lesson is an extremely exciting lesson--probably my favorite of the whole course--0004

because we are going to be teaching you how to create your own user-defined functions,0009

which is really going to increase your efficiency as a PHP programmer.0012

Specifically, we are going to talk about how to define your own functions, and the syntax that is involved with that.0018

We are going to talk about function parameters, which is ways to pass data to functions.0024

We have previously talked about that when calling functions using function arguments.0029

We are going to talk about return statements, which allow you to return a value from a function,0033

because, as we had learned before, functions are expressions, and they have values.0037

We are going to discuss where to define functions within your PHP code, 0043

and that is going to involve a discussion of the include_once construct, 0047

which is an extension of the include construct that we have talked about before.0052

And we are going to also talk about some reasons why you use functions, and why to separate code out into functions.0056

Then, we are going to make an update to our web application, version 10.0, 0063

where we are going to extract some of the code from it and put it into functions, 0068

so we can see our user-defined functions working firsthand in our web application.0073

And then, we are just going to quickly talk about when you do output HTML in functions, and then also coding conventions as it relates to functions.0079

Defining a function requires four parts: it requires the function keyword (and this is an example of a function declaration);0091

you provide a function identifier or a name of the function; then, in parentheses, you provide what is known as a parameter list0100

(we are going to talk more about that in a minute), and then, just like a control structure, 0108

you have a statement group enclosed in parentheses, and that contains all of the code that gets executed when a function is called.0112

And this section of a function is known as the function body--the code contained in the function is known as the function body.0120

Anything contained, any PHP code that we have gone over so far, is allowed anywhere else in PHP script.0127

One thing to mention is that function identifiers or function names follow the same naming rules as we have for variables and constant identifiers.0135

Let's take a look at some examples of some basic functions, and see how they work.0146

Here, we have a sample script called functionExamples.php, and right here, this function is an example of the most simple function.0153

It is a function that, when it gets called, does nothing.0164

It has no statements in it, which is a perfectly legal function.0167

Now, as we know, when we call a function, it stops execution of the current script, goes and executes the code in the function,0170

and then returns the value to the script where it was called from; and then, the script continues to execute.0178

So here, in this case, we have defined this function; and then, I am going to go ahead and just call it.0183

And the way we do that is: just as we have been calling built-in PHP functions, we have the function name with the parentheses and a semicolon.0191

And this function does nothing, but it shouldn't cause any problems or any errors, and when we load the page, nothing should happen.0200

But this is just to demonstrate that a function can contain anything, including the lack of any code.0206

If we load functionExamples.php, nothing happens.0215

The other thing we can do is: we can create a function that just has one statement in it, but it is an empty statement.0220

And again, this is just to emphasize the fact that functions contain statements, and they contain any types of statements, including an empty statement.0233

And if we go ahead and call this function, we should receive no output, as well.0243

I'll go ahead and load the page, and nothing happens.0249

So now, we are going to get a little more interesting: we are going to have our function do something.0254

We are going to create an example function that is going to output some code by an echo statement.0259

So, we have this function called example1_2, and all we are going to do is simply echo a statement that says "inside example," and then the function name.0269

So, when we go ahead down here, below the function, and we call this function, example1_2,0284

what is going to happen is: when we reach this statement right here, it is going to call the example1_2 function.0297

It is going to run the code inside of it, which in this case is just an echo statement, 0303

and it is going to echo that statement, and then continue processing the rest of the script.0306

So, we should see this line output now, when we run the script.0310

And when we reload the page, you can see, the echo statement was output that we had in the function.0316

So now, I want to talk about something called function parameters.0330

Function parameters are variables that are defined when you define a function, and they are variables that can be used within the function body.0335

They are described in between the parentheses of a function definition; and you can have as many parameters as you need.0344

When you call a function, as we have seen with built-in functions to PHP, we can supply data to functions.0351

And those are called function arguments; the data you supply is called an argument, and the argument fills the parameter variables of the function.0359

For example, when we define this function with param, we define it as having one parameter called param.0369

And what that means is that we can access this variable, param, anywhere within the function body.0377

And here, we can see that we just echo the value of param.0383

And the way that that gets said is by...when you call the function with param, you provide a function argument.0385

And what happens is: param gets set to this value.0394

So, every time this function is called, whatever value is supplied as an argument to the function--this parameter will get set to that value.0402

Now, I use the term parameter and argument, and it's sort of a technical distinction.0413

Technically, when you define a function, and you create (I'm erasing this) a parameter list, the variables that you make available0416

in the function definition are known as function parameters.0431

And when you call a function, you call a function with arguments, and those are the values that the parameters are going to get set to.0437

And sometimes, you will hear those terms used interchangeably; but essentially, they refer to kind of the same thing.0443

When you call a function, you supply arguments which set the value of the parameters specified in the function definition.0448

And you can have multiple parameters in a function, and what happens is: let's say, for example, there was another parameter here--0456

the way that it would get set (let's call it param1) is: when we call the function, we would supply a second function argument.0469

The order that the functions are supplied in specifies the order that the parameters get set in.0482

So, the first parameter gets set to the value of the first argument; the second parameter gets set to the value of the second argument.0494

Let's go take a look at some functions that use parameters.0502

So here, we have another example function that we are going to create that is going to take one parameter.0513

And all that it is going to do is echo the parameter that gets passed in.0518

For example, when we call this function, it requires one parameter, so we are going to have to supply it a value that it can output.0526

So, we are going to supply it with a string; and when we call the function...let's supply it with the string "Hello, World!" for example...0533

Now, what is going to happen is: when we call this function, this code is going to stop executing right here.0548

It is going to go up to where the function is defined; it is going to set the parameter variable, 0554

this param variable, to the argument specified, which was "Hello, World!"0560

And then, it is going to run the code in the function body, which just says to output the parameter variable, 0565

which is the string value that was passed in.0571

So, when we run our code, we should see it output this string "Hello, World!"0574

And if we go and take a look at that (oops, I had a typo; I forgot an e down here), you can see that it output "Hello, World!"0580

And if we include a break statement up here, this will look nicer...or actually, let's just get rid of this function call.0601

We can see that "Hello, World!" is output.0618

And the unique thing about function parameters is: they can be set to a different value every time the function gets called.0622

And that is what makes the function useful: it allows you to dynamically do things.0629

It can do one thing in one instance...for example, output one string one time it is called, 0632

and then output another string when it is called a different time.0637

So, for example, we could input to this function the string "Goodbye" and then now, when we call this same function again,0640

even though it is the same function, it is going to perform a slightly different action, based on the arguments that we specified.0651

So, when we load it now, it is going to output this new string statement that we passed in.0660

Let me go ahead and comment out this line.0669

And now, what we are going to do is demonstrate, using a function that has multiple defined parameters.0672

Here we have a function with two parameters called param1 and param2.0679

What I am going to have it do is create a string that is just the concatenation of both parameters.0684

So, these parameters are both going to be strings that get passed in, and then we are going to create a string inside the function0691

that is just going to be the concatenation of those two strings, using the dot operator.0699

And we are just going to echo this concatenated string.0708

When we call this function, example2_1, we provide it with two parameters.0718

In this case, we provide it with "Hello," and then, as a second parameter, we provide it with the string " World!"0725

So now, when we call this function--when we execute this function call--it is going to take these two strings.0741

It is going to set the value of param1 in this function to Hello,; it is going to set the value of param2 equal to World!.0747

And then, the function is going to execute, and it is going to execute the concatenation of those two strings.0753

We should, again, see the string "Hello, World!" output.0761

If we go and reload the script, we can see, "Hello, World!" was output.0764

As we know from our Introduction to Functions lesson, functions are expressions.0775

What that means, that we know about expressions, is: they have a value.0780

So, functions always have a value, and they always return a value to the script that they were called from.0783

And the value of a function is known as its return value, and return values in PHP can be any type.0790

It can be an array; it can be a scalar, as we learned; it can be an object.0801

The way that you specify the return value of a function, or the value that it returns to the script it was called from, is using a return statement.0807

One thing to note, that we are going to show an example of in a second, is that you can have multiple return statements within the same function.0817

What happens is: when a function is executing, any time it reaches a return statement, 0824

it automatically ends execution of the function and returns whatever value it was set to return in the return statement.0830

And even if there are statements that are still unexecuted in the function, it doesn't matter.0839

Once that return statement is reached, the function ends, and it returns back to the execution of the current script.0842

One other thing to note is that, if a return statement never occurs, or is never executed, within a function,0848

null is the value returned by default for all functions.0855

Let's go take a look at the return statement in action.0859

The first thing we are going to do is: we are going to have the return value...0870

we are going to use a return statement that is just going to return a static value.0873

So, it's going to have it return the string "Goodbye," and then we'll call the function, and this is a function with no parameters.0877

What is going to happen when we call this function in this statement right here: example3_0 is going to get called,0898

and what it is going to do is: it is going to execute the function body of example3_0.0907

And we see in the function body that all it contains is a return statement.0912

So, what this is going to do is: when this function reaches this return statement, 0914

which is the only statement in the function, it is going to return the value Goodbye.0918

And that is how the return statement works: the statement starts with the return keyword, followed by a space, 0923

and then whatever value you are going to return, which could be an expression; 0929

it could be the output of another function, because functions have values.0934

Basically, you can return anything with value.0936

When this gets called, example3_0 is going to get executed; its value is going to be inserted here, and its value is going to be the return value Goodbye.0939

So, this is going to echo the return value Goodbye, and so the script should output Goodbye.0947

If we go ahead and reload the script, we can see that that is what happens.0955

So now, one thing that we are going to talk about that we had mentioned was that you can have multiple return statements within a single function.0966

For example, if we have a function that accepts one parameter, we can maybe conditionally return a value, based on the value of that parameter.0976

For example, we create an if statement that says, "If param equals the integer 1, 0986

then we are going to execute a return statement that is going to return the string 1."1000

"Alternatively, if param equals 2, we are going to have it return the string 2."1007

So in this case, when this function gets executed, you can see that there are two return statements.1023

If param is equal to the integer value 1, it enters this if statement block, and it executes this return statement, and the function exits.1027

So, none of the remaining code gets executed.1034

If parameter equals 2, it is going to not enter this if block; it's going to enter this elseif block, and then it is going to return the value 2.1038

We could additionally add an echo statement here that says, for example, param is not equal to 1 or 2.1045

And also, what happens with a function is: if no return statement is specified, 1059

the function just returns whenever it executes the last statement within the function.1063

So here, if param doesn't equal 1 or 2, this statement is going to get executed.1070

However, if it does equal 1 or 2, the function is going to return up here or right here.1074

And this echo statement won't get executed, or if param is equal to 1, none of this will get executed, as well.1080

That demonstrates a function that can have multiple return statements.1088

For example, if we call this function (and we are just going to echo its output, because it is returning string values),1093

let's put the value of 1 in; so it should enter this first section of code; it should return the value of 1.1111

And then, because it returns, the rest of it shouldn't get executed; so this echo statement should not occur.1119

When we run this code, we can see, it outputs 1.1125

Likewise, if we just change this down here to the value 2, we can see that it outputs the value 2, 1130

and it never gets to this echo statement here, because again, once you reach a return statement, the function stops executing.1140

The other thing I wanted to demonstrate is: we have mentioned that, if a function doesn't have a return statement, it automatically returns the value null.1148

So, if we just have an empty function here, with a single statement that does nothing, and then we were to run the function,1158

we are going to run a comparison on the value returned by the function, to see if it is equal to null.1168

And we should find out that it is true.1173

So, if we run the comparison example3_2, what we are saying here is: we are running a comparison operation that is saying,1176

"call function example3_2, compare it to returned value (which in this case should be null, 1193

because no return statement was explicitly specified); it should equal null, 1197

and because it equals null, this statement should be true."1202

And with echo statements, the boolean value true gets output as the value 1.1208

That is the conversion from a boolean true to a string.1214

So, when we run this, we should see just the number 1 output; and that is confirming that this returns the value of null.1217

When we run the function, we can see that 1 is output, meaning that it did, in fact, return the value of null.1224

We have talked about how to define functions; we have talked about defining them with parameters and defining them with return statements.1236

We haven't really talked about where to define functions.1243

Typically, functions get separated into their own PHP files, known as function libraries, usually grouped according to the task they perform.1247

You might have 4 or 5 different functions, for example, that perform tasks on arrays.1255

So, you might create a function library that contains all of those functions.1261

And the function library only contains the PHP code for those functions.1265

It is just a PHP file that contains all of the function definitions.1271

And the way you access the file is by using an include statement; so if you are running a PHP script, 1279

and you need to access, for example, an array function that you have defined in a function library, 1284

you include that function library by an include statement, and then you will be able to have access to the function.1289

Now, one thing to note is: unlike some programming languages, in PHP, a function definition does not need to occur before it is called.1297

You can call a function and then define it later in the script, 1308

or call a function and then include the function library where it is defined later on in the script, and it will still work.1311

As long as the function that you are calling is defined somewhere within a script, within the script it is being called from1318

or an include file of that script, it will work.1324

The way you typically include functions, and what we are going to use in this course (or include function libraries within your code) is1332

using a new construct that we haven't talked about, called include_once.1338

It is similar to the include construct, and what it does is: it takes the file that is specified and includes it in line, in the file where the include statement happens.1344

The one difference is that, with include_once, if you specify a file to include, and it has already been included, it won't get included again.1356

For example, if in this single PHP script we have this one statement, include_once ('functionLIB.php'), 1369

which maybe is a function library, and somewhere in the script, we had another include_once function that says functionLIB.php,1376

it is not going to re-include it, because it has already been included once.1385

The reason that this is used with function libraries, as opposed to using an include statement, is:1389

if you redefine a function within the same PHP script, you get a fatal error in PHP.1394

For example, if you accidentally include the function library twice within your script, 1400

using just regular include statements, you are going to get a fatal error.1405

And similar to include, include_once also has an analog, which is called require_once, which functions the same as the require statement,1410

which throws a fatal error if it can't find the file it is trying to include.1418

But it also functions like include_once in that, if you call require_once on the same file 1422

multiple times in one script, it only gets included the first time.1428

Let's go take a look at a script that demonstrates this ability.1432

We have a file called includeOnce.php, and here we have another file called functionLIB.php.1438

This is a file that is just a function library; it contains a couple of different functions.1446

Here, in this case, we have a function called test, and a function that we are going to use in another example called outputHtmlHeader.1453

What happens is: let's say we want to use the test function within our script.1460

And let's get rid of this include statement--comment this out.1467

Now, when we run this file, we should get an error saying that the function is not defined,1471

because the function hasn't been included or been defined within this file.1476

So, if we go ahead and load the file up, it is going to say "Fatal error: undefined call to the function test."1480

OK, so we need to include the function library in order to have access to that function.1488

So, what we can do is use an include statement, include 'FunctionLIB.php'.1494

And this test function just simply outputs a simple statement; it says, "in test."1499

Now, when we run the file, everything should be OK; and it goes ahead and runs.1505

Now, however, let's say we accidentally, later, down here in our script, forgot that we had included that function library already,1509

and we run an include statement again, and try to call test again.1519

Well, we are going to get a fatal error here, because FunctionLIB.php is going to be included twice.1524

And because FunctionLIB.php has the definition of two functions in it, and it is called twice, 1529

PHP is going to see those functions being redefined, which is a fatal error.1537

So now, when we run our script, which has these two inclusions of the same function library, we are going to get a fatal error.1541

And we can see "Fatal error," and it tells you what we would expect: you cannot re-declare test.1550

It says that test, defined in the FunctionLIB, cannot be re-declared.1556

The way to fix this problem is if we use include_once on both of these statements.1568

And if we always use include_once when including function library files, we won't have this problem.1572

It is going to include FunctionLIB.php here; it is going to call the test function; 1580

and then, when we try to include it again, later on down the file, it is going to say, "Hey, I have already included this file;1585

I'm not going to include it again," and you eliminate getting that fatal error for trying to redefine the function.1589

If we save this file now, we should be able to run test twice.1597

We go ahead and load the file; we can see, we get that test was run; it says "in test" here twice.1602

Similarly, we can mentioned, there is an analog require_once that does the same thing,1610

except it returns a fatal error if the file you are trying to require or include cannot be found.1623

So, we should get the same output, because it works.1630

And what that means is that this function was not included a second time.1632

Now again, the way require differs from include is that, if it can't find the specific include file 1636

(for example, if I mistype the name of it), it is going to throw a fatal error.1643

So, if we run the file, it is going to say "Fatal error": require_once wasn't able to open this misspelled function library.1647

And so, that is the difference between require and include.1657

What are the reasons to use functions?1666

The main reason, or one of the major reasons, is to take advantage of code reuse.1670

What that means is: if you have a common task that you are performing over and over again,1675

you can isolate the code into one spot (into one function), and then you can just call that function over and over again, as you need it.1678

What that does is: that is going to limit your mistakes to one place.1685

The mistakes can only occur within that one function, whereas, if you had, for example, 5 lines of code that were included in the function,1690

if you include those 5 lines of code everywhere (in 5 different files, for example), that is 5 different places where a mistake can occur.1697

If you take that code out, put it in a function, and replace it with a function call,1706

then if there is an error in that code, you only have to fix it in the function file.1712

Additionally, if you want to (for example) change the functionality of something,1718

what you can do is apply the changes all in one place.1723

So again, if you use a function call (for example) to display something, and you want to change how it is displayed,1726

instead of going through each file, editing the code that displays it,1733

if you put that code within a function, you can just go ahead and apply the changes that need to be made in one spot,1737

and it goes ahead and applies it to all the other things.1743

So, this is going to increase your efficiency as a programmer; it is going to allow you to get things done faster.1745

Additionally, it is going to allow you to reduce writing the same functionality repeatedly.1751

For example, let's say you spend a couple of hours one day developing a couple of functions that you use for working with arrays.1756

Well, maybe you have another PHP project down the road, and you want to use some of those same functions.1763

Well, by including them as functions in a function library, you can reuse those in your new PHP application.1770

If you hadn't separated them out as functions (had just hard-coded them into your PHP pages),1776

when you went to your new project (for example), you wouldn't be able to just include the function library and reuse it.1781

So, separating things into functions allows you to reuse them, not only within one application, but in multiple applications.1791

The other thing that you can use functions for is to improve code readability.1798

That is by separating your HTML and PHP.1803

Typically, you want to separate (and this is something we haven't really talked about) your HTML and PHP as much as possible,1806

because it makes for cleaner-looking code, and also, when you are working on a team (for example)1814

you might have people that are HTML developers and people that are PHP developers.1819

The less you intermingle the HTML and PHP with one another, the easier it is 1822

for different teammates to work together, without messing up one another's code.1831

If the HTML developer only works with HTML files with minimal PHP code, the chance of him messing up the PHP is limited.1836

Likewise, for a PHP developer, if he is only working with PHP files that have very little HTML, the chance of him formatting the HTML incorrectly is reduced.1845

So, you can use functions (for example) to remove large sections of PHP code from mixed HTML and PHP files.1854

You might have a 200-line PHP page, and maybe 25 of those lines are PHP code.1865

Well, what you can do is separate it out into a function, and then, 1872

when your HTML developer goes to edit the HTML on that page, all they see is one function call.1875

They don't see the 25 lines of code that that developer has a chance to mess up.1881

Another thing that you can do is...sometimes, you just have ugly mixes of HTML and PHP code.1890

When you use echo statements, you have a lot of escaping with backslashes to output quotation marks, and so on.1897

So sometimes, if you have smaller "ugly" sections of mixed HTML and PHP code, you can separate that out into a function.1905

And what that is going to do is make your PHP page that is actually output look cleaner.1916

You are not going to have to look at the messy PHP and HTML mixed together.1924

Instead, you can have it in a function, so that ugliness only occurs in one spot.1927

The other thing that some people use is: you can essentially use a function as a way to include HTML content--to replace include files.1934

That is something you might see on different projects that you work on; you might see different developers use it.1944

For example, we have a script called functionVsInclude.php.1952

Here, we are including a function library, using the include_once statement we just learned about.1964

And the reason we are doing that is because it contains this function called htmlHeader.1969

What this htmlHeader does is outputs (for example) the header of an HTML page.1973

Maybe we want to include this at the beginning of every page.1980

So, what we could do is: in our page, we could go ahead and call outputHtmlHeader.1983

And what it is going to do is take the echo statements that are in that function, run them, and then output that.1990

Now, we could achieve the same thing by using an include statement...1998

for example, if we included this file called header.html, 2003

which contains all of the same HTML that is output by this outputHtmlHeader function, and instead, we include it in here.2007

So, basically, there are two different ways of doing the same thing.2015

Some people like using functions to do that; maybe, instead of using an include statement for a header and a footer, 2017

you have two functions called outputHtmlHeader and outputHtmlFooter; it is a preference thing.2024

You may see that in different spots.2032

And one thing to also note is that here, we have all of these echo statements.2034

But as we know, with PHP you can always escape to HTML mode.2038

So, we actually could replace all of these echo statements with the exact same content that we have in header.html.2042

What is going to happen is: when we run this outputHtmlHeader, it is going to execute what is in its function body.2060

And what is in the function body is an escape to HTML and an output of HTML code.2067

And then, at the end of the function, it just returns.2074

So, that is another way to output HTML, as well.2077

So now, let's talk about improving our web application.2083

We are going to move to version 10.0, and we are going to 2086

take advantage of what we have learned about creating user-defined functions to clean up our code a little bit.2089

In checkout.php and contactUs.php, there are some rather complex boolean expressions used to validate the form data submitted.2097

For example, in checkout.php, we validate that a name, a street address, a city, a ZIP code, and so forth, were all provided.2108

It makes a complex boolean expression.2116

In contactUs.php, we verify that all three (name, email address, and comment) were submitted on the form.2120

We are going to separate those boolean expressions out into a function that is just going to return a boolean.2126

It is going to return true or false; and they are going to be called validation functions.2131

What that is going to do is make our code look cleaner, because, 2137

instead of having these long, ugly PHP statements, we have a single function call.2140

We are also going to create a function that is just going to be used to output HTML <a> tags, or anchor tags, which are HTML links.2146

It is going to allow us to pass in (for example) a URL and the name of the link that we want,2156

and it is going to dynamically create an HTML string that uses the URL and name provided.2160

We are also going to add a constant to config.php that is going to be called LIB_DIR.2168

What that is going to do is: we are going to put these functions into function libraries, and we are going to store them in a lib directory.2174

And, just as we created an INCLUDE_DIR constant in our config file, we are going to create a LIB_DIR one2181

that is just going to be a path to where we are going to store all of our function include files.2186

What we are going to be doing is creating two library files, stored in the lib directory, one called outputLIB.php, and one called utilLIB.php.2192

That is the convention we are going to use in this course for signifying function library files.2204

You will have a descriptive name for the functions that are included in the file, 2209

and then it is going be ended with the three capital letters LIB as part of the name.2214

And that is going to let you know, when you look at that file, that this is a function library.2220

This function library, outputLIB.php, is going to be used for functions that do any sort of outputting of HTML.2225

And then, utilLIB.php is going to be used for utility functions.2232

For example, that is where we are going to put our validation functions; 2239

they are functions that perform utility operations you can use within your web app.2241

So, we are going to edit checkout.php and contactUs.php.2247

What we are going to do is take out the complex boolean expressions and replace them with the validation function.2252

We are going to edit config.php, so that it has this updated content, LIB_DIR.2259

And then, we are also going to update store.php to make use of the function we are going create up here2264

that is going to allow us to create HTML anchor tags.2269

Let's go take a look at the code; for example, if we look at version 9.0, if we look at checkout.php (this is version 9.0),2276

and if we scroll down to where we do the data processing, we can see that there is one section down here2296

where we are validating the shipping information that was provided by the customer.2304

And if you look, this is a particularly ugly and complex boolean expression that is validating all of the data.2308

And so, what we can do is take that out and put it in a function that returns the boolean value of that expression.2317

And then, we can replace it with a single function call, and that is going to make it look cleaner.2324

For example, we replace that boolean expression; instead, we just have a function call down here, called isValidCustomerData.2328

And the function name has a descriptive name; typically, functions that return boolean values have is prepended to them, as the first part of the name.2338

So, isValidCustomerData is going to tell us about whatever we are passing here--is this valid customer data?2350

And so, we are getting the same functionality, but we are doing it in a simpler, cleaner statement.2358

Likewise, in contactUs.php, we validate the form to make sure that an email, comments, and name were provided.2366

What we can do is take this boolean expression out, and replace it with a simple function call that says isValidContactInfo.2375

Now, the other thing that provides is: let's say, later down the road, for these validation functions, we want to provide more validation.2384

Maybe we want to say that "state" has to be a certain state, or for the contact information, that an email address has to meet a certain format.2391

For example, it has to have an @ symbol; it has to have the domain name and the username as part of it.2400

Well, we can add that to this isValidContactInfo function, and this line right here will never change.2405

That added code won't show up in our HTML file.2412

So, we are going to keep the PHP and HTML as separate as possible.2415

And what that is going to do is allow us to change the functionality, but we don't have to change this code here; it is going to keep this code looking clean.2420

So, if we go to the LIB directory of version 10.0 and open up utilLIB.php, we can see these two functions that we have created.2428

The first one was called isValidCustomerData, and what we do is, from checkout.php, pass it the customerData variable, 2442

which is an associative array that represents all of the GET data passed to checkout.php.2452

It goes ahead and uses this customerData parameter, and what it does is performs the same validation function that we had in the script.2459

It says, "Just make sure that each of the different fields are not empty."2466

If all of them are not empty, it is going to return true, so that we can know that it's valid, and proceed as appropriate in our checkout.php.2470

Likewise, for the contactInfo validation, we have an isValidContactInfo function.2483

We pass it the contact information that was submitted on the Contact Us form, and we perform the boolean validation function.2491

If it returns true (that all of the information was provided), then it returns true to our script, and it can go ahead and execute.2500

When it calls this, if this is true, it outputs the appropriate page title (for example).2508

If not, we are going to use our error functionality and set up an error message saying "You must complete all of the fields in this form,"2513

and also set our error flag (that we had talked about in previous versions) to true.2520

The other thing that we are going to do is create a function that is going to allow us to output HTML links, or <a> tags.2529

For example, if we look at version 9's store.php, we can see, we have a link hard-coded into each page2538

that is a link to each different item in the catalog (item-1001, 1002, and 1003).2545

What we can do is create a function that will allow you to pass two parameters or arguments to it,2552

one for the URL of the link that is going to be used for the href, and then also one value 2560

that you can put in the body of the link, that is contained in the a tag.2566

If we open this other library file called outputLIB.php, we can see a function called outputLink.2571

It accepts two parameters, both of which are strings: a URL and a body.2580

And what we can see is that it creates a link variable; and what it does is dynamically creates an a tag.2585

It sets href equal to the URL specified; it sets the body of the a tag equal to the body specified.2598

This is a useful function, because this is one of the ways of eliminating ugly PHP/HTML mixed code from your file.2606

And it is not too prevalent in this example, but we will see it more, as our application gets more advanced,2616

and our URL's that we are using, and our expressions to set the value of URL's, get complex.2623

This is going to neaten them up, because now, instead of having a statements, which included echo statements from PHP,2628

we have replaced it with simply a call to outputLink, which we echo.2642

And we pass it the URL that we want (in this case, for item-1001), 2648

and then we provide it the name that we want to be in the tag (which is going to be the item's name).2652

And we do that for all three of these.2658

And if we go and look at version 10.0, this is the store home page.2661

We can see, if we look at the source, that our links are just as they were before, except they have been created by this outputLink function.2672

And they work just as they had before.2686

One thing to note: if you have a chance, after the lesson, to look closer at the files that we have created,2693

particularly function libraries, you can see that to each function, I have added a lot of comments at the beginning.2702

It is always good to add comments that provide a lot of information to the programmers about your code.2710

For a function, I usually have a comment that states the purpose--what the function does.2716

In this case, it is saying it is outputting a link that is an a HTML tag, an anchor tag.2722

I also described the parameters that the function takes, so somebody can quickly look at this and say,2729

"OK, it takes 2 parameters, one called url and one called body, and this is what they represent."2734

"The url represents what is going to be used in the href attribute with the anchor tag, 2738

and body represents the text that is going to be output as the body of the anchor tag."2744

And then, I also have a return value section that says, "This function returns a string, 2748

and the string that it returns represents a well-formed HTML anchor tag."2753

How do we make these functions available to our scripts?2762

That is where the config file comes in; we have updated config.php, and what we have done is created a new constant called LIB_DIR,2764

which states that the function library directory is called LIB, and it is off of the document root.2781

And that is where all of our function libraries can be found.2791

And then, what we do is add to our include section, using the include_once directive.2794

We include each of the two libraries that we are going to use, outputLIB.php and utilLIB.php.2799

This is going to make them available to all of the files where config.php is included.2806

You can see that we make use of the LIB_DIR constant, which says that output.php is in this LIB directory, and you include it one time.2810

And so, that is how we make those functions available to our web application.2819

One thing I want to comment on is outputting of HTML in functions.2827

It is usually preferable to refrain from directly outputting HTML within functions by echo statements or HTML, when it's possible.2831

The reason for that is that, if you have function libraries (for example) in multiple different library files in your code,2840

and you are calling different functions and different scripts,2847

and one function in one library outputs some HTML; another function in another library outputs some HTML...2850

it makes it hard for your HTML editors (which may be you, or it may be a separate person) to figure out2856

where they can go to edit the HTML, so that it is output properly.2862

So, by not outputting HTML in your functions, and only doing it in the actual PHP pages that are going to be shown,2865

it allows the person editing the HTML to find it all in one location.2874

Now, sometimes it is necessary to output HTML within functions, and the recommendation that I have2880

is to put output functions in their own separate library.2887

So, for our example, in this web app, we have created a library called outputLIB.php2890

because that generates HTML (in this case, it generates anchor tags).2897

We are going to build out that library as this application develops, and you are going to see that there is going to be more complex HTML output.2902

But by putting it in that one library, your HTML developer knows that if the HTML that they need to edit is not found 2909

in the actual PHP pages that are being output, then it is going to be found in this function library that is defined for output functions.2915

One other thing to mention is that, if you have some functions that generate short segments of HTML2923

(for example, our outputLink function that just generates a link to output),2929

it is highly preferable to generate the HTML content as a string and return that string, rather than echoing it directly in the function.2934

For example, in our outputLink function, we return this link that we created.2943

We could, instead, just echo it directly here--echo link--and we would achieve the same thing as what we had done before,2952

if we just replaced the echo statement here with outputLink.2964

So, it's going to call outputLink, and it is going to echo that.2967

Now, there are a couple reasons why that is not preferable.2969

Let me go back and change it to the way it was.2973

The first one is that it reduces the flexibility of your application.2978

For example, if we return the string, then in the store.php, because we are returning it as a function and not directly outputting it,2981

we can perform another operation on it, whereas if it just gets echoed, it is echoed to the output and there is nothing you can do with it.2993

Maybe we want to include that HTML as all uppercase, so we could use the strtoupper function.3001

Well, because we returned it as a string, we could use that string as a value supplied to the strtoupper function.3007

And then, when we echo it, we can make it all uppercase.3013

And so, it gives us the flexibility of altering that; and in this case, it's a function chain.3018

So, when we go and reload our home page, we can see that (I guess I just did it for the second one, item-1002) it is output in all uppercase.3023

And if you look at the page source, you can see that even the HTML code itself, href and all that, was capitalized, as well.3040

That is one thing that is a benefit of returning a string, rather than echoing it directly.3053

The other thing is that, if you want to create complex echo expressions--for example, let's say we wanted to echo3060

the string "Hello" and then output that link by concatenating it--what is going to happen is: right now, it is going to work as expected.3070

It is going to output Hello; it is going to call the outputLink function, return that <a> anchor tag, and then output it all together.3086

So, if we go and view our code (oops, I forgot to get rid of the extra parentheses here), we can see that3094

it outputs Hello, and then it outputs the anchor tag, as expected.3115

Now, in our outputLink function, if we had instead echoed it directly, something interesting is going to happen.3120

Now, when we call this function, it is going to say "echo this string right here."3134

And in order to echo this string, what PHP is going to do is concatenate the output of outputLink to Hello.3141

Well, in order to do that, it has to call outputLink and find out what its value is.3149

So, when outputLink gets called, because we have echoed the link now, it is going to echo it.3153

So, before this concatenation can occur, outputLink is going to be echoed; so the link is going to end up before Hello.3159

For example, if we go ahead and run this file, we can see that, even though in the echo statement, we have put the outputLink3167

tag at the end of the concatenation operation and Hello at the beginning, the order gets reversed.3179

And that is because, since the function didn't return the string, we can't concatenate it in our echo statement.3184

Instead, it just gets output immediately when it is evaluated.3191

That is one of the problems that that can cause.3195

Just really quickly, I want to finish up with talking about coding conventions.3198

Functions, as you have seen in the examples, are going to be formatted in the same manner that we format if statements,3202

in regards to the placement of curly braces and indentation, the one difference being 3209

that the if keyword is going to be replaced by the function keyword.3213

The other thing is functions with multiple parameters: each function in the parameter list is going to be separated from the previous one3217

by a comma and a space, so it is going to be param, and this is going to be a space before param2,3225

as opposed to not having the space there.3235

The other thing that we are going to do is: we are always going to define all of the functions for our course within function library files.3238

You can define them within a script, but then that reduces the ability to reuse those,3244

because then, for example, if you defined it in contactUs.php, if we defined in a email function within there, for example,3250

then if we ever wanted to use that again, we would have to include that whole PHP page.3258

And so, in order to get access to that function, what that is going to do is include all of the HTML, as well.3262

So, we are going to include all of our functions in library files.3267

For the homework challenge, I just want you to create a PHP script that is going to create a function called add, your first user-defined function.3275

It is going to accept two integer parameters, and what it is going to do is return a string that is the sum of those two integers,3284

surrounded by the bold tags used in HTML.3291

It is going to take in two integers, and it is going to return a string.3296

And then, I want you to call the function from your script and output the result.3299

And what that is going to do is a couple of things: it is going to teach you how to define your own function;3303

it is going to teach you how to use multiple parameters in a function;3310

it is going to teach you how to use a return statement; and then, it is also going to echo 3313

the comment that I had about returning strings, as opposed to echoing them directly.3317

Then, what I want you to do is get practice creating function libraries: go ahead and create a function library called mathLIB.php.3323

And put the function within that file; and then, in your main script, when you have moved it out, it gets deleted.3331

And then, use an include_once statement (to get practice using that) to include that LIB file in your script.3338

And then, try calling the function again, to make sure it still outputs the sum, formatted in bold.3344

Just be sure to remember to format the function according to the course's coding conventions.3349

That ends today's lecture; thank you for watching look forward to seeing you next time.3355