PHP Functions
PHP Functions
A Function is nothing but a 'block of
statements' which generally performs a specific task and can be used repeatedly
in our program. This 'block of statements' is also given a name so
that whenever we want to use it in our program/script, we can call it by
its name.
In PHP there are thousands of built-in functions which we can
directly use in our program/script.
PHP also supports user defined functions, where
we can define our own functions.
A function doesn't execute when its defined, it executed when
it is called.
PHP User Defined Functions
We can declare and call user-defined functions
easily.
Syntax:
<?php
function function_name(){
// function code statements}
?>
Example:
1.
<?php
2.
function sayHello(){
3.
echo "Hello PHP Function";
4.
}
5.
sayHello();//calling function
6.
?>
Output:
Hello PHP Function
Advantages of User-defined Functions
As we have already seen a simple example of using a function
above, you must have understood how time-saving it can be for large programs.
Here are a few advantages of using functions for you:
- Reuseable
Code: As it's clear from the example above, you write a
function once and can use it for a thousand times in your program.
- Less Code
Repetition: In the example above we just had one line of code in
the function, but what if we have 10 lines of code. So rather than
repeating all those lines of code over and over again, we can just create
a function for them and simply call the function.
- Easy to
Understand: Using functions in your program, makes the code more
readable and easy to understand.
Comments
Post a Comment