PHP Function
By:- Jalpesh Vasa
PHP Functions
• Heart of well-organized script
• Block of code that is not immediately
executed, but can be called by your script
when needed.
• Basically 2 types:
 Built-in
 User-defined
PHP Functions(Built in)
• PHP Array Function
• PHP Calendar Function
• PHP class/object Function
• PHP Date/Time Function
• PHP Directory Function
• PHP Error Handling Function
• PHP File System Function
• PHP MySQL Function
• PHP Network Function
• PHP String Function
• PHP ODBC Function
• PHP XML Parsing Function
PHP Functions (Built-in)
• include() – include content of one file to php
file.
 gives warning if file not found and
continuing executing script
• require() - compulsory include the specified
file.
 gives fatal error and stops executing script
furhter .
PHP Functions (Built-in)
• Eg. <html><body><h1>hello</h1><p> ok</p>
<?php include(‘a1.php’);?>
<?php include ‘a1.txt’; ?>
</body></html>
• Eg. <body>
<h1>Welcome to my home page!</h1>
<?php include 'vars.php';
echo "I have a $color $car.";
?>
</body>
<?php
$color='red';
$car='BMW';
?>
vars.php
PHP Functions (Built-in)
• Eg. <html><body><h1>hello</h1><p> ok</p>
<?php include ‘vars1.php’;
echo “you have $color $car”;
?>
</body></html>
• Eg. <body>
<h1>Welcome to my home page!</h1>
<?php require 'vars1.php';
echo "I have a $color $car.";
?>
</body>
<?php
$color='red';
$car='BMW';
?>
vars.php
PHP Functions(User defined)
• Information to be passed to them & usually
return value.
• Function name are case-insensitive
• All function require parenthesis
• Defining a user-defined function:
function fun_name(arg1,arg2)
{
----
----
}
PHP Functions
<?php
function bigh()
{
echo “hello”;
}
bigh();
Bigh();
?>
PHP Functions
<?php
function printB($txt)
{
echo “$txt<br>”;
}
printB(“This is line”);
printB(“hello”);
printB(“hi”);
?>
PHP Functions
<?php
function addnum($n1, $n2)
{
$result = $n1+$n2;
return $result;
}
echo addnum(3,4);
?>
PHP Functions
• Dynamic function call
It is possible to assign function name as strings to
variables & then treat variables exactly function name
itself.
<?php
function say()
{
echo “hello<br>”;
}
$fun_name = “say”;
$fun_name();
?>
PHP Functions
• Variable declared within a function remains
local to that function
 not available outside function or within other
function
function hello()
{ $var1 = “hi”;
echo “variable is $var1”;
}
PHP Functions
$var2 = “hello”;
function f1()
{
echo “variable is $var2”; //inaccessible
}
f1();
PHP Functions
$var2 = 42;
function f1()
{ global $var2;
echo “variable is $var2”; //accessible
}
f1();
PHP Functions
function foo()
{
function bar()
{
echo “hi”; // doesn’t exist until foo is called.
}
}
PHP Functions
function be($h=30)
{
echo $h;
}
Be(450);
be();
be(21);