PHP Tutorial: Creating New Functions in PHP

Intro

Functions are important and most useful tool in any programming language and are very easy to create / build one. Functions can be called as building blocks (like "bricks in wall") in developing any type of software (web software's, desktop applications etc.). As always said, software is a collection of programs and those programs are none other than functions holding a special task of that upcoming software. Functions simplify our work by allowing us to lessen complex code from our scripts and if once created, we can use them multiple times in our future projects according to our needs by upgrading them.

PHP Functions

Php functions are very easy to create and it's syntax is shown below.

function anyFunctionName()
{
	your code;
}

Function names can start either with a letter or with underscore ("_") sign, not with any number. Here, below is the simple example of php function doing mathematical calculation.

<?php

function aDDITION($value1,$value2){
	$sum=$value1+$value2;
	return $sum;
}

echo aDDITION(5,6);

//above echo will output the result (I mean, it'll print result on the screen)

?>

In the above php code,

  1. $value1 and $value2 are two parameters (inputs) that will be accepted by this function before executing,
  2. After receiving inputs, this function will add those values and will store the sum in '$sum' variable,
  3. Then, it will return value of '$sum' as output,
  4. You need to echo this function with appropriate parameters to print output on the screen or you can do as shown in code below.

<?php
function aDDITION($value1,$value2){
		$sum=$value1+$value2;
		echo $sum;
		}
?>

So, it is that simple to create and use functions in php. Here is one useful point on using php functions.

  • Instead of printing the output directly from function itself, you can return final result via using this php command ' return $yourVariable; ', So that, you can use that outputted result in other functions also, as shown below.

<?php

function add($v1,$v2){
	$sum=$v1+$v2;
	return $sum;
}

function newFN(){
	$result=add(4056,53894);
	echo $result;	
}

newFN(); 
//above line will act as trigger to begin execution.
?>

Thanks for reading

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working