Old 14-05-2007   #1 (permalink)
chX
GotGames Moderator
 
chX's Avatar
 
Join Date: Jan 2007
Location: Adelaide
Age: 17
Posts: 3,760
Rep Power: 5
Send a message via MSN to chX
Default Chaos' PHP Tutorial - Part 4: Functions.

Chaos' PHP Tutorial - Part 4: Functions.

Hello everyone! It's been a few weeks since my last tutorial but rest assured there are plenty more coming!
Today we will be looking at functions in PHP, both custom and in-built.

Functions.
What is a function exactly? Well, the best way to describe a function is a segment of code which is put together in a wrapper for a purpose. We can call them to output values or do something. Functions are very useful for keeping your code neat, tidy and flexible.

The Function Syntax.
The syntax of functions is as follows:

PHP Code:
function <function name> (arguments)
{
// Some code, possibly a statement to execute

Let's have a look at that syntax. You first write "function" -- this is to let PHP know it is actually a function. You then name the function, which could be anything you want. We'll have a look at the arguments part in a second.
There are the common curly brackets and inside of those go some kind of code.

So how does this look in action?

PHP Code:
function printName()
{
echo 
"My name is Chaos!";

You need to define a function somewhere in your code to use it; it is often useful to make a separate PHP file just for functions.

You can then call the function like so:

PHP Code:
printName(); 
This would then print "My name is Chaos!" to the page.

So what's this arguments stuff I was on about before? Arguments are basically values (or variables) you can pass into a function.
It's hard to explain them in any more detail, so how about I just show you.

PHP Code:
function printName$name )
{
echo 
"My name is $name!";

Now you have setup a function but you have also defined an argument. In this case it is $name. You can also see that rather than having "My name is Chaos!" printed, I have "My name is $name!"

Now we can call this function again.

PHP Code:
printName("Chaos"); 
Which would output the following:

My name is Chaos!

We could also change it...

PHP Code:
printName("Nuk3"); 
Which would output:

My name is Nuk3!

As you can see this makes functions very versatile. However, this is not the only thing we can do with functions.

Returning a Value.
Rather than, say, printing out a value to a screen, we might want to return that value. Once again the best way to explain this is to demonstrate it.

PHP Code:
function calculatioN($x$y)
{
   
$total $x $y;
   return 
$total;

This creates a function called calculatioN (I did that with the N because I want to be cool ) and also gives it two arguments; $x and $y. Then we assign the ADDITION of $x and $y to the variable of $total. We then say to return $total.

PHP Code:
$number 0;
echo 
"The variable number is equal to $number!";

$number calculatioN(10,20); # This will store the result of the function calculatioN in the variable of $number.
echo "The function has been run and now the variable of number is $number!"
Which would output:

Code:
The variable number is equal to 0!
The function has been run and now the variable of number is 30!
That's all on creating your own functions for now, but there are many in-built functions already there for use.

In-Built Functions List.

mail()
The purpose of this function is to allow e-mails to be sent from within PHP. This is common on forums where after registration you receive an activation e-mail.

PHP Code:
$to "blah@blah.com";
$subject "This is an e-mail using the mail function.";
$headers "From: someone@somewhere.com";
$message "Look out behind you, the mail function will eat you!";

mail($to$subject$message$headers); 

strtolower()
This function converts a string of text into all lowercase.
PHP Code:
$string "HELLO THERE!";
$newstring strtolower$string ); // Outputs "hello there!" 

strtoupper()
Exactly the same as previous, except it converts everything to uppercase.
PHP Code:
$string "hello there!";
$newstring strtoupper$string ); // Outputs "HELLO THERE!" 

ucfirst()
This function capitalizes the first character in a string and also makes every other character lowercase.
PHP Code:
$string "hELLO THERE!";
$newstring ucfirst$string ); // Outputs "Hello there!" 

ucwords()
The purpose of this function is to capitalize the first letter of every word in a string.
PHP Code:
$string "hello there!";
$newstring ucwords$string ); // Outputs "Hello There!" 

strlen()
This function determines the amount of characters in a string.
PHP Code:
$string "Hello there!";
$newstring strlen$string ); // Outputs 11. 

include()
This is a very useful function. It is used to include and evaluate other files. If you were to make a PHP file full of functions,
you could use include() to import the file into another PHP file and thus make all of those functions available.
PHP Code:
// Include a functions file
include("functions.php");

// Call the functions from that file
calculatioN(3,5); 
Well, that's about it on functions for today. I'll be pumping out more tutorials soon. As always, if you have any questions or comments feel free to PM me or post in the thread.

--Chaos.

Last edited by chX; 14-05-2007 at 05:18 PM..
chX is offline   Reply With Quote
Old 14-05-2007   #2 (permalink)
Pro Member
 
nuk3's Avatar
 
Join Date: May 2006
Location: Sydney, Australia
Posts: 6,539
Rep Power: 9
Default

Might wanna mention global/static variables, and also how to set default values for the function arguments.

PHP Code:
function calculatioN($x$y)
{
   
$total $x $y;
   [
i]return[/i$total;

vBulletin owned you there
__________________
OM NOM NOM
nuk3 is offline   Reply With Quote
Old 14-05-2007   #3 (permalink)
chX
GotGames Moderator
 
chX's Avatar
 
Join Date: Jan 2007
Location: Adelaide
Age: 17
Posts: 3,760
Rep Power: 5
Send a message via MSN to chX
Default

Quote:
Originally Posted by nuk3 View Post
Might wanna mention global/static variables, and also how to set default values for the function arguments.

PHP Code:
function calculatioN($x$y)
{
   
$total $x $y;
   [
i]return[/i$total;

vBulletin owned you there
Haha. GRR!
chX is offline   Reply With Quote
Old 14-05-2007   #4 (permalink)
Contributing Member
 
Join Date: Jun 2006
Posts: 607
Rep Power: 3
Default

Hey.

A wrapper perhaps is not the best desc, however In this context it does work. Remember though that functions execute on a stack and have their own scope.

Functions more aptly are pieces of code that perform a specific task and are generally quite independent of other code in the program. They can then return a value to whomever called the code and when they exit (return) all the local variables in the functions are cleaned up.

When programmers talk about a wrapper we generally considered it to be (in programming speak) a piece of code that allows code/functions/classes/libraries to work together that normally would not be able to. For example, A wrapper for a C++ SSL library so it works in PHP. (in this case data marshaling and exposing an interface in php that maps to the c++ libraries interface).

Some other things that should be covered:

Scope - This is quite important and remember php is different to C and many other languages, where a global scope is automatically available in the local scope.

Static - The static keyword in functions, for example

PHP Code:
function myCount() {
 static 
$i;
 
$i++;
 echo 
$i
}

myCount(); // 1
myCount(); // 2
myCount(); // 3 
And also passing by reference aka
PHP Code:
function swap(&$a, &$b) {
 
$a ^= $b;
 
$b ^= $a;
 
$a ^= $b;
}
$a 1;
$b 2;
swap($a$b);
// $a now == 2 
Global - The global keyword, its nasty but its there

And perhaps you might want to put a note in about
func_get_args which allows you to have a number of arguments (it can be a handy func).

And lastly, yes nuk3 covered it, defaults are handy
function a($need, $optional = true);

And one last thing, maby people miss is the difference and uses between these functions:

require
include
include_once
require_once

Might highlight that to as it is useful to any developer.
__________________
92% of teens have moved on to rap. If you are part of the 8% who still listen to real music, copy and paste this into your signature.

Last edited by Khaless; 14-05-2007 at 05:58 PM..
Khaless is offline   Reply With Quote
Old 14-05-2007   #5 (permalink)
chX
GotGames Moderator
 
chX's Avatar
 
Join Date: Jan 2007
Location: Adelaide
Age: 17
Posts: 3,760
Rep Power: 5
Send a message via MSN to chX
Default

There's a lot of stuff I haven't included in the tutorials. That's mainly because it is aimed at beginners, trying to give them a little bit of insight into PHP one step at a time. That's the reason I use the analogies and descriptions or terms which people who are not adapt to PHP can relate to better.

Perhaps I can write advanced tutorials later, but at present it's just a dip in the shallow end rather than jumping into the deep end.
chX is offline   Reply With Quote
Old 14-05-2007   #6 (permalink)
Contributing Member
 
Join Date: Jun 2006
Posts: 607
Rep Power: 3
Default

Quote:
Originally Posted by ChaosX View Post
There's a lot of stuff I haven't included in the tutorials. That's mainly because it is aimed at beginners, trying to give them a little bit of insight into PHP one step at a time.
Ahh yes, but my argument has always been that if you dont, they may otherwise never be exposed to it, and this do weird things. Which i assure you (having taught 1st year uni students) is ALWAYS a great problem.

Perhaps having a box like this:
Quote:
Originally Posted by Advanced Content!
stuff...
So that you can include it, and if they want to read it and understand it they can, otherwise they may skim over it and know it can be done, which is always important.

I guess its like the lazy execution pattern.. hehe lazy learning, yep its there i know it is.. i can now learn it when i need it.
__________________
92% of teens have moved on to rap. If you are part of the 8% who still listen to real music, copy and paste this into your signature.
Khaless is offline   Reply With Quote
Old 15-05-2007   #7 (permalink)
Monster Member
 
jamiec's Avatar
 
Join Date: Sep 2006
Location: irc.gamesurge.net
Posts: 4,922
Rep Power: 7
Send a message via MSN to jamiec
Default

Wow you guys are really smart, how much on this have you done to learn all this chaos.
__________________
Man donates blood to save his Mrs. A year later they break up. He says "give me my blood back b**ch". She throws him a tampon and says "f**k you, I'll pay you back monthly".
- lividscott.
jamiec is offline   Reply With Quote
Old 15-05-2007   #8 (permalink)
chX
GotGames Moderator
 
chX's Avatar
 
Join Date: Jan 2007
Location: Adelaide
Age: 17
Posts: 3,760
Rep Power: 5
Send a message via MSN to chX
Default

Quote:
Originally Posted by _fatz View Post
Wow you guys are really smart, how much on this have you done to learn all this chaos.
I've been learning HTML and PHP for about 4 years. It's really not that hard to learn, once you know what everything does.

I started by actually memorizing entire pages of code... which didn't help me at all. Sure, I could write the entire code down on notepad and produce something that works, but I lacked understanding and without understanding you can't manipulate or change the code to make something else.

It was really when I took the time to understand what everything did rather than just knowing the words.
chX is offline   Reply With Quote
Old 15-05-2007   #9 (permalink)
Contributing Member
 
Join Date: Jun 2006
Posts: 607
Rep Power: 3
Default

Seconded. Understanding is the most important thing.

To many times now i see people just cut and pasting.
__________________
92% of teens have moved on to rap. If you are part of the 8% who still listen to real music, copy and paste this into your signature.
Khaless is offline   Reply With Quote
Old 15-05-2007   #10 (permalink)
Pro Member
 
chemicalNova's Avatar
 
Join Date: Jun 2006
Age: 19
Posts: 5,593
Rep Power: 8
Default

Quote:
Originally Posted by ChaosX View Post
I started by actually memorizing entire pages of code...
Wow, I did that too. I remember sitting in grade 4 and typing out an entire webpage with friends watching. The main focus was some Javascript buttons that took on a theme which you could change with a function call.

chem
__________________
There are no stupid questions... but there are alot of inquisitive idiots.
-
chemicalNova is offline   Reply With Quote
Old 15-05-2007   #11 (permalink)
chX
GotGames Moderator
 
chX's Avatar
 
Join Date: Jan 2007
Location: Adelaide
Age: 17
Posts: 3,760
Rep Power: 5
Send a message via MSN to chX
Default

Haha yeah. I first memorized an entire login script with sessions and all. Anyone can just cut and paste some code but if there are errors or problems and you don't have an understanding... you're screwed.
chX is offline   Reply With Quote
Old 15-05-2007   #12 (permalink)
Contributing Member
 
Join Date: Jun 2006
Posts: 607
Rep Power: 3
Default

Quote:
Originally Posted by ChaosX View Post
Haha yeah. I first memorized an entire login script with sessions and all. Anyone can just cut and paste some code but if there are errors or problems and you don't have an understanding... you're screwed.
QFTT.

And it becomes spaghetti code.
__________________
92% of teens have moved on to rap. If you are part of the 8% who still listen to real music, copy and paste this into your signature.
Khaless is offline   Reply With Quote
Old 15-05-2007   #13 (permalink)
Pro Member
 
nuk3's Avatar
 
Join Date: May 2006
Location: Sydney, Australia
Posts: 6,539
Rep Power: 9
Default

Quote:
Originally Posted by Khaless View Post
And it becomes spaghetti code.
What, good on toast?
__________________
OM NOM NOM
nuk3 is offline   Reply With Quote
Old 15-05-2007   #14 (permalink)
chX
GotGames Moderator
 
chX's Avatar
 
Join Date: Jan 2007
Location: Adelaide
Age: 17
Posts: 3,760
Rep Power: 5
Send a message via MSN to chX
Default

Quote:
Originally Posted by nuk3 View Post
What, good on toast?
Ohhh nuk3 made a funny!

I like my code warm with a side of cheese.
chX is offline   Reply With Quote
Old 16-05-2007   #15 (permalink)