Functions


User-defined Functions

User-defined function can help to reduce size of source code and to give easy analyzation. You can define frequently used code as a function and then call only function name whenever you need. A function consists of name, argument, statement and return value. The naming rule is the same as variables.

User-defined function name
The first letter The rest
Alphabet or _(underscore) Alphabet, number or _(underscore)
Syntax Description
function name(argument)
{
  statement;
  return value;
}
Create function with specified name
Multiple or no argument can be allowed
return or return value can be omitted
Syntax Description
name(argument1, argument2, ...); argument can be referenced by variable
function name is case-sensitive
<?php

function func()        // define function func()
{
  echo "Hello PHPoC";
}
func();                // call function func()

?>
  • Example of return value of Function
<?php

function func()        // define function func()
{
  return 5;
}
$var = func();         // call function func()
echo $var;

?>
[result]  
5
  • Example of Using Arguments
    Information may be passed to functions via the argument list, which is a commadelimited list of expressions.
<?php

function func($arg)   // define function func() with $arg
{
  return $arg + 1;    // add one to $arg, then return it
}
$var = func(2);       // pass function func() to 2, then receive 3
echo $var;
$var = func($var);    // pass function func() to $var(= 3)
echo $var;
$var = func($var+1);  // pass function func() to $var+1(=5)
echo $var;

?>
[result]  
346
  • Example of Recursive Function Call
    Functions can be called inside a function including itself.
<?php

function func($arg)   // define function func() with $arg
{
  if($arg < 6)
  {
    echo "$arg\r\n";  // print value of $arg
    $arg++;           // increases $arg by one
    func($arg);       // call function func() and pass func() $arg
  }
}
func(1);              // call function func() and pass 1 for argument

?>
[result]  
1
2
3
4
5