PHP Functions
Learn Functions in PHP (Part-1)
PHP provides a plenty of functions. We can create our own functions too, they are called user-defined function. So In PHP, functions can be classified into two types, one is built-in, and the other one is user-defined. In this tutorial, you are going to learn how to create and use your own functions in PHP. You will also learn what are the uses of functions and how many ways you can define your function and how to call those functions.
What is a Function in PHP
A function is a block of code with some name.
Function will perform some operation ex: addition, subtraction, multiply…etc.,
Advantages of functions:
1. managing programs becomes easy.
2. functions can be reused. So that it saves memory and time.
3. Error handling becomes easy.
4. functions can be used in multiple programs once they defined in one program
Creating Function
Structure of the function
function functionName(arguments) { code to be executed; return value; }
Defining and Invoking Functions
syntax:
function functionName() //function definition
{
code to be executed;
}
functionName() ; // function call
Example:
<?php
function hello() {
print("Hello world! <br>");
}
hello();
?>
Why Functions
A program without function.
In the below program, if you execute all operations (addition, subtraction, multiplication)
are performed at once, one after another, as we have written.
<?php $a =10; $b =20; print "<br />Addition of 2 numbers is ". ($a+$b); $a =40; $b =20; print "<br />Subtraction of 2 numbers is ". ($a-$b); $a =30; $b =20; print "<br />Multiplication of 2 numbers is ". ($a*$b); ?>
Output:
Addition of 2 numbers is 30
Subtraction of 2 numbers is 20
Multiplication
of 2 numbers is 600
But the same above code if written in the form of functions, so you can control the execution of each operation.
A program with function
<?php function add() { $a =10; $b =20; print "<br />Addition of 2 numbers is ". ($a+$b); } function sub() { $a =40; $b =20; print "<br />Subtraction of 2 numbers is ". ($a-$b); } function mul() { $a =30; $b =20; print "<br />Multiplication of 2 numbers is ". ($a*$b); }
sub(); //calling sub() mul(); //calling mul() ?>
Output:
Subtraction of 2 numbers is 20
Multiplication of 2 numbers is 600
In the above program, add() function not called, so it will not be executed. Only substation and multiplication functions get executed.
Continue to
Comments
Post a Comment