Thursday, 27 June 2013

PHP: Functions

A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!


For example, you might have a company motto that you have to display at least once on every webpage. If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this sounds like a situation where I might need functions."


Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don't give up if functions confuse you at first!


creating your first php function

When you create a function, you first need to give it a name, like myCompanyMotto. It's with this function name that you will be able to call upon your function, so make it easy to type and understand.


The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that. First, you must tell PHP that you want to create a function. You do this by typing the keyword function followed by your function name and some other stuff (which we'll talk about later).


Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the code for myCompanyMotto.


PHP Code:

<?php

function myCompanyMotto(){

}

?>


Note: Your function name can start with a letter or underscore "_", but not a number!

No comments :

Post a Comment