1 of 7

Web Technologies

Functions in PHP

Smt.M.Jeevana Sujitha

Assistant Professor

Department of Computer Science and Engineering

SRKR Engineering College, Bhimavaram, A.P. - 534204

2 of 7

OBJECTIVES

The Objective of this lecture is

  • To learn about Functions in php.

3 of 7

Functions

  • A function is a piece of code which takes one or more input in the form of parameters and does some processing and returns a value.

Creating user defined function:

  • A user defined function declaration starts with the keyword “function”

and all the php code should be put inside curly braces.

Syntax:

function function-name(par-list)

{

Code to be executed;

}

Example:

<?php

function display() //called function

{

echo "welcome to php functions";

}

display(); // calling function

?>

4 of 7

Functions

PHP function arguments:

  • Information can be passed to functions through arguments.
  • An argument is just like a variable.
  • Arguments are specified after the function name, inside the

parentheses.

  • We can add as many arguments as we want, just separate them

with a comma.

Example:

<?php

function add($a, $b) //called function

{

echo $a+$b;

}

add(10,20); // calling function

?>

5 of 7

Functions

PHP default arguments:

  • We can set a parameter to have a default value if the function caller does not pass it.

Example:

<?php

function setHeight($height=50) //called function

{

echo $height;

}

setHeight(200); // calling function setHeight();

?>

6 of 7

Functions

Dynamic Function calls:

  • It is possible to assign function name as strings to variables and then treat these variables exactly as we would the function name itself.

Example:

<?php

function display() //called function

{

echo “haiii”;

}

$show=“display”

show(); //calling function

?>

7 of 7

THANK YOU