Introduction to PHP - User Defined Functions Part 1

Guest Posts Paolo Nikko Nuñal

Just like any other programming language, PHP can also create functions, in which the language already has 1000 built-in functions. Aside from PHP user defined functions, you can also create your own.

So you might ask, what is a PHP function.

You can summarize them into three definitions namely:


  • PHP functions are a block of statements that can be used repeatedly in a program.

  • PHP functions will not execute after a page loads.

  • PHP functions will be executed when it is invoke or called.


Creating a PHP function is easy and all you need to do is start with the reserve word "function".

Syntax:

<?php
   function myFunction()
   {
        //INSERT CODE HERE
   }
?>


There are a few things that you should know about functions. The first thing is that a function name can start with a letter or underscore but never a number.

Functions can easily be called by calling the name of the function.

Syntax:

<?php
   function myFunction()
   {
       echo "Function myFunction is called";
   }

   myFunction();
?>


From the code above, we are able to call the function myFunction by simply writing myFunction(). After which, whatever is inside the function will be run, in our case, the example will print a string.

Functions are useful if you are dealing with code repetitions and it simplifies your algorithms eliminating redundancies.