Home arrow PHP arrow Page 2 - Basic and Not so Basic "Function" Features Using PHP
PHP

Basic and Not so Basic "Function" Features Using PHP


Jason has written this article for those who are in the need of learning how to use functions in PHP. Covered in this article will be issues relating to OO programming.

Author Info:
By: Jason Lam
Rating: 5 stars5 stars5 stars5 stars5 stars / 36
April 18, 2003
TABLE OF CONTENTS:
  1. · Basic and Not so Basic "Function" Features Using PHP
  2. · The Article

print this article
SEARCH DEVARTICLES

Basic and Not so Basic "Function" Features Using PHP - The Article
(Page 2 of 2 )

The Basics

Okay for those of you who are new to PHP we will go over the basics first.  What is a function?  A function is a way to encapsulate a set of code.  In other programming languages functions are sometimes referred to as methods or procedures.  As well some languages even make distinction between procedures and functions. 

In PHP there are just functions, though with object oriented programming the function in the class are sometimes referred to as methods to be consistent with OO terminology, lets save that for another article.  The following reasons why one would want to use functions are:

Code Reuse, for example you want to calculate the salary for several employees you could reuse the same calculation for each every employee with out re-coding it

Easier code maintenance, using the last example, it is a lot easier to update or fix bugs in one place rather then change the same code in several different places.  This also lessons the chance of you making a mistake in one or more those different places with the same code.

Makes your code a lot more modular and therefore a lot more readable instead of one huge giant program or script from top to bottom.  Take a look at the following code, mind you it isn't entirely correct but you should get the point:

employees = getEmployees();
results = calculateSalary(employees);
showReport(results);

You can see from here things are broken into 3 basic parts getEmployees, calculateSalary and showReports.  All three are self-explanatory and moreover easier to read and understand.

Okay now that we know why to use functions what makes up a function, this is best illustrated by simple HelloWorld code.

function helloWorld() {
 echo "Hello World";
}

To use the sample code all you have to do is call the function name helloWorld(), in this case there are no parameters.  The next example includes one parameter where you pass in the words to be printed:

function helloWorld($yourWords) {
 echo $yourWords;
}

The function now needs to be called with a parameter, you simply call the function with correct parameter(s), in this case it would be helloWorld("Hello World").  Yes a function can accept a number of parameters, for example helloWorld("Hello","World"), of course the function needs to be defined to accept the correct number of parameters.

If you want the function to return a value all you have to do is include the return statement in your function, take for example you want the helloWorld to return a response.

function helloWorld($yourWords) {
 echo $yourWords;
 return "GoodBye";
}

 OR

function helloWorld($yourWords="GoodBye") {
 echo $yourWords;
 return $returnValue;
}

 OR

function helloWorld($time) {
 $result = getResponse($time);
 if ($result == 1)
   return "Good Morning";
 if ($result == 2)
  return "Good Afternoon";
 if ($result == 3)
  return "Good Evening";
}


In this last example we changed it a little to demonstrate you can call functions within functions as well you can have multiple return statements however only one will ever be returned based on the condition statements.

In all cases only one value can be returned from a function.

In the second example you will notice function helloWorld($yourWords="Good Bye")  assigns a value for $yourWords, this called default assignment.  If the function helloWorld is called without parameters then $yourWords by default will be assigned the value "Good Bye".

Another feature functions are capable of is the ability to access global variables, for example

$globalVariableHello = "Hello World";
$globalVariableGoodBye = "Good Bye"
function helloWorld() {
 global $globalVariableHello; //global declaration
 echo $globalVariableHello;  // access global variable
 echo $GLOBALS["globalVariableGoodBye"];  // access $GLOBALS array
}

It is recommended not to use global variables and or multiple return statements.  It will save you a lot of hours of debugging.  The rule thumb is one entry point and one exit point.  An alternative to multiple exit points is simply use a variable:

function helloWorld($time) {
 $returnResult = "";
 $result = getResponse($time);
 if ($result == 1)
   $returnResult = "Good Morning";
 if ($result == 2)
  $returnResult = "Good Afternoon";
 if ($result == 3)
  $returnResult = "Good Evening";
 return $returnResult;
}

An alternative to global variables when you want to maintain the value within a function is to use static variables:

function counter() {
 static $count = 0;
 return $count++;
}
echo counter();
echo counter();
echo counter();

Output:  0 1 2

The static variable value is retained even after the execution of the function is complete, as you can see in the above example $count is incremented each time it is called.

Going Beyond the Basics

Returning More then One Value

Previously it was mentioned a function couldn’t return more then one value.  This is still true but there is a way to do indeed return more then one value.  Simply make the return value an array. This is especially useful when your web application is broken up into layers/tiers and you want to be able to pass the error/exception from a lower tier to the top, so the user gets a more user-friendly error message.  An example:

function db_update_user_info($dbConnection,$userInfo) {
// Notice in this example only one parameter for user information called $userInfo, this is // because this variable is an array
 // define the return value
 $result = array();
 $result[0] = false;   // this indicates if the call was successful
 $result[1] = "";   // this stores any error messages
 $result[2] = "";       // this stores any results for successful execution
 // code goes here
 return $result;
}

You can see this function db_update_user_info returns more then one value, this example is for illustration purposes.  You may want to clean it up, for example you may want to use string for index names and the error messages and successful results could actually share index 1, $result[1], rather then create 3 indexes.

Pass By Reference

This is not really an advance feature but rather an understanding of what kind of parameter is being passed in.  By default passing in parameters to a function it is passed in by value meaning a copy of that variable is passed in. If manipulation is done to that copy (inside the function) the original variable outside the function retains the same value assuming no code outside the function updated it.

Your other option is to pass in variables by reference this is indicated by the ampere sign symbol, &.  Meaning if the function does updates to the variable it affects the original variable outside the function.  This is because the function is not accessing a copy of the variable rather the address of where the original variable resides.

An example passing in by value:

$theVar = "hello world"
doChange($theVar);
echo $theVar;
function doChange($theVar) {
 $theVar = "good bye"
}

Output:  hello world

An example passing in by reference:

$theVar = "hello world"
doChange($theVar);
echo $theVar;
function doChange(&$theVar) {
 $theVar = "good bye"
}

Output:  good bye

Dynamic Functions

To create a function based on a condition.  This is better explained with an example:

Example 1:

$theVar = 1;
if ($theVar==1) {
  function helloWorld() {
   echo "Hello World 1";
  }
} else {
  function helloWorld() {
   echo "Hello World 2";
  }
}
helloWorld();

Output: Hello World 1

Example 2:

$theVar = 2;
if ($theVar==1) {
  function helloWorld() {
   echo "Hello World 1";
  }
} else {
  function helloWorld() {
   echo "Hello World 2";
  }
}
helloWorld();

Output: Hello World 2

The implementation of helloWorld function is created based on the value in $theValue, it is as simple as that.

Another way to dynamically create a function is to create an anonymous function a function without a name:

$anonymousFunction = create_function('$arg1,$arg2','echo $arg1 . " " . $arg2;');
echo $anonymousFunction("Hello","World");

Output:  Hello World

This may seem a little confusing at first because the function doesn't have name, instead the created function gets assigned to a variable, from there you use the variable directly as if it was the function.

Variable Indirect Function
 
Variable/Indirect functions is actually a call to the PHP function $process_function() which then processes the set function, the set function is what is held in the variable $process_function.  For example you could indirectly call the helloWorld() by doing the following

$process_function = "helloWorld";
$process_function();
function helloWorld() {
  echo "Hello there";
}

Output:  Hello There

Now to do a variable indirect function call look at the following code first:

$menuOption = 2;
switch ($menuOption) {
 case 0: process_option0; break;
 case 1: process_option1; break;
 case 2: process_option2; break;
 case 3: process_option3; break; 
};
function process_option0() {
  echo "Option 0";
}
function process_option1() {
  echo "Option 1";
}
function process_option2() {
  echo "Option 2";
}
function process_option3() {
  echo "Option 3";
}

Output:  Option 2


To eliminate some code you may want to consider using indirect function calling, as well it makes easier to maintain your code all you have to do is add the new function you don't have to worry about updating any if or switch statements.

$menuOption = 2;
process_function = "process_option$menuOption";
process_function();
function process_option0() {
  echo "Option 0";
}
function process_option1() {
  echo "Option 1";
}
function process_option2() {
  echo "Option 2";
}
function process_option3() {
  echo "Option 3";
}

Output:  Option 2

Notice process_option$menuOption is the function name but name itself is contains a variable.  Depending on what the variable is the called $process_function will call the appropriate function assuming that function indeed exists.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
PHP ARTICLES

- Removing Singletons in PHP
- Singletons in PHP
- Implement Facebook Javascript SDK with PHP
- Making Usage Statistics in PHP
- Installing PHP under Windows: Further Config...
- File Version Management in PHP
- Statistical View of Data in a Clustered Bar ...
- Creating a Multi-File Upload Script in PHP
- Executing Microsoft SQL Server Stored Proced...
- Code 10x More Efficiently Using Data Access ...
- A Few Tips for Speeding Up PHP Code
- The Modular Web Page
- Quick E-Commerce with PHP and PayPal
- Regression Testing With JMeter
- Building an Iterator with PHP

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials