So far we’ve been using PHPs built-in functions to do our tasks; we also declared and used user-defined function in the post Creating a Simple Visitor Counter in PHP. However, we didn’t discuss much about them. For those of you who are curious to know more about user-defined functions or those who’d doubts, I’ve written this post. Read along to know more about user-defined functions.
Declaring functions
In PHP functions are declared using the keyword ‘function’ as below:
function func-name(arg-list)
{
…
}
Here ‘arg-list’ may be empty if you don’t want the function to take any arguments.
If you remember from the post Creating a Simple Visitor Counter in PHP, we’d stated that no matter whether the function returns a value or not, no return type has to be specified for the function (unlike C/C++).
a. Functions having parameters
function myfunc($a)
{
echo $a;
}
b. Functions returning values
function myfunc($a)
{
return 2*$a;
}
Scope of variables inside and outside of function
-
Variables declared inside a function are called local variables and re only accessible within the function.
-
Variables declared outside functions are called global variables STILL they are NOT directly accessible from inside functions.
Have a look at the following code:
function myfunc()
{
$a=10;
}
echo $a;
//$a will not be accessible
//for global varaible
$a=10
function myfunc2()
{
//again $a not accessible
echo $a;
}
There is nothing we can do to make local variables accessible outside the function however global variables can be made accessible inside functions by explicitly defining that particular function as ‘global’ inside the function.
$a=10
function myfunc2()
{
global $a;
//now $a=10 is accessible
echo $a;
}
Naming functions
-
Two functions cannot have the same name neither your functions can have the same name as an existing function. PHP DOES NOT SUPPORT FUNCTION OVERLOADING.
-
Function name may have letters, digits and underscores.
-
Function name cannot begin with a digit.
-
Functions can be of the same name as a variable though.
Previous Articles: