Introduction to Functions

on Fri Nov 21 14:38:30 GMT 2008 in PHP and viewed 3532 times

An introduction to how to make simple functions using PHP.


Functions. They can be very useful when building a website. On instance for example is a function I use for BBCode. Functions provide easy to use and re-usable pieces of code that you can take advantage of.

To start, there is the basic statement to start a function.


function name(){
//statements go here
}

To explain this, “function” says that “name” is a function. () is the part where you list any arguments, something I’ll cover later. { and { are the standard code block opening and closing curly braces.

Now you can put almost anything inside a function. Here’s just a simple function to display the classic “Hello World” statement.


  function hello(){

  echo "Hello World.";

  }

There! That function, when called, will output “Hello World” to the screen. Now we get to how to call a function.


  function hello(){

  echo "Hello World.";

  }

  hello();

That’s really it.

Now we’re going to deal with arguments. Arguments are just values you’ll put inside the parantheses () so the function can interact with other things outside the function.

Here’s a function to add two numbers using arguments.


  function add($number1, $number2){

  $number3 = $number1 + $number2;
  return $number3;

  }

Now this’ll be a bit different. Here it’ll create the variable $number3 and it’ll also return it in the function. That’s something I’ll discuss next. Now here’s basically how that function will work.


  function add($number1, $number2){

  $number3 = $number1 + $number2;
  return $number3;

  }

  $variable = add(1, 2);//sets $variable to 3 after the function has worked
  echo $variable;//outputs 3 to the screen
  echo add(1, 2);//does exactly the same as the two statements above, but shorter

Now in this kind of function, you have to set it to a variable, and this is why a return statement is important. Since I’m returning $number3, that’s what $variable will be set as, or that’s what will be echoed. Without the return statement, the file wouldn’t know what to set the variable to.

So after everything, functions really help in organizing code and making it easier.