Introduction to Functions

Posted 11 months ago at 4:34 pm. 0 comments

Hello again,

Welcome to my first real article. In this post I will be discussing functions, specifically in PHP. I am assuming you know basic PHP syntax, but if you don’t, it is easy enough to learn on your own.

In PHP there are 2 ‘types’ of functions. There are the ones that are there by default, and then the ones that you, personally, create. The ones that are there by default are very basic, and fundamental. The ones you will soon learn how to create yourself accomplish things like cleaning up the code, condensing the code, avoiding redundancy, and making it easier to read all around.

Examples of default functions include: include(), echo(), print(), etc…

Custom functions are made up by you. Here is an example.

function sayHelloWorld(){
echo "Hello World!";
}

With that included into your script, you can now write just write

sayHelloWorld();

And it will output “Hello World!”

As you can see, this is in fact a lot neater. While this is a simple example, it shows the power of functions. Say you wrote about 100+ lines of code for a login script, you could just make it into one big function that looks like this…

function loginUser($username, $password){
//code
if('foo' == 'bar'){
return true;
}else{
return false;
}
}

Now in that example, you might have seen something I haven’t talked about. Arguments.

function loginUser($username, $password){

the two variabls separated by the comma are called arguments. This is how you talk to the code, and give in information to work with. In that example, for the function’s ‘blue print’ if you will, I’m saying that when I call the function, I will be providing it with those two variables in that format. So lets say I wanted to directly call this function, I would write
loginUser('wildwobby', 'thisismypass');
And then, the function will replace all the instances of the $username with the value of wildwobby, and all instances of $password with the value of thisismypass.

The other thing you probably see is the
return true;
return false;

While it doesn’t make sense in my example without any real code, you would set it up so the function returns true if in fact the login was successful and false if it wasn’t. This is how the function talks back to you. you could put it into an if statement, and if the login went successful, it will execute the script within the if statement.
if(loginUser('wildwobby', 'thisismypass')){
echo "You have been logged in!";
}else{
echo "Sorry, there was a problem with the login.";
}

This concludes the introduction to functions. Hopefully you know enough to start playing with this new wonderful skill of yours. Don’t hesitate to comment and let me know what you thought. Also, be sure to play around with php trying a bunch of random stuff on your own as it is truly the way to learn how to program!