PHP 5 Functions

A function in PHP, and any other programming language, allows you to encapsulate a piece of code and call it from other parts of your code. This makes it possible to write code which can be re-used from different parts of your application, without actually writing the code over and over again. Here is an example of a simple PHP function:

Example -

A function should always start with the keyword function, followed by the name of the function you wish to declare. In this case, we name our function SayHello. It should be followed by a set of parentheses, which allows you to define parameters for the function. Parameters are not required, but if you don't have any, you should still write the parentheses, like SayHello(). With our function, we define the $to parameter. Since PHP is a typeless language, you don't have to define a type for the parameter, and you may send any kind of datatype through the function. The content of our function is between a set of curly braces, in this case a simple echo statement, where we use the $to parameter to send a greeting to a specific person or thing.

Example -

A very important aspect of functions is the scope. Once you enter a function, you enter a new scope, and while functions and classes are automatically global, variables are not. This means that a variable declared outside a function is not automatically available inside it. Try this example to see it for your self:

Example -

PHP Functions - Returning values

To let a function return a value, use the return statement:

Example -